Skip to content

readme - #3

Merged
ataibarkai merged 8 commits into
mainfrom
atai/0714/readme
Jul 14, 2023
Merged

ataibarkai merged 8 commits into
mainfrom
atai/0714/readme

Conversation

@ataibarkai

Copy link
Copy Markdown
Contributor

No description provided.

@ataibarkai
ataibarkai merged commit 52b7127 into main Jul 14, 2023
@ataibarkai
ataibarkai deleted the atai/0714/readme branch July 14, 2023 18:52
@github-actions github-actions Bot mentioned this pull request Jan 9, 2025
yungscotia pushed a commit to yungscotia/cia-platform-copilotkit that referenced this pull request Jun 6, 2025
johnprg pushed a commit that referenced this pull request Dec 23, 2025
jpr5 added a commit that referenced this pull request Apr 17, 2026
…d remove brittle source-grep

Two R15-6 follow-ups in the test file:

#2: the 'readonly arrays' test only asserted Array.isArray(...) on
both members, which is trivially true — the real contract is a
TypeScript-only compile check, not a runtime property. Swap the
assertion for something that IS verifiable at runtime: successive
auditPackage() calls return freshly-built (not shared) arrays, so a
caller mutating one return value can't corrupt the next.

#3: remove the '[source-lint] main() body uses process.exitCode'
test. Its regex (/function main\([^)]*\)[^{]*\{([\s\S]*?)\n\}/) is
brittle — any minor reformatting of main() or its surroundings can
change which '\n}' matches first. The behavioural subprocess test
that asserts the stdout drain still works ('emits the full summary
table on stdout even when exiting non-zero') already covers the
property we care about end-to-end. A comment block at the former
location documents why it was removed so future readers don't
re-add an equivalent fragile source-grep.
jpr5 added a commit that referenced this pull request Apr 18, 2026
…ip + isMainPath catch coverage

R17-3 #4: validateAll EACCES test now asserts r.status === 3 strictly. The prior expect([1,3]).toContain defeated the fix it was meant to guard — accepting the pre-fix behavior (1). Restructured the fixture to chmod the parent dir (not the file) so statSync in collectDepsFromDir fails EACCES → infra: true → UnreadableInputError → EXIT_UNREADABLE (3) actually fires. chmod'ing the file routed through readFileSync (not-infra parseError → EXIT_DRIFT), never exercised the fix.

R17-3 #2: parseRequirementsTxt dropped-line test uses '==1.0.0' — an operator-leading line with no package name is GUARANTEED to be dropped by parseRequirementsLine (leading [A-Za-z0-9] required). Replaced the silent early-return guard with an invariant assertion that fails loudly if the fixture ever stops producing a drop.

R17-3 #3: parsePyprojectToml skipped-entry test drops the early-return guard; the Poetry git-only inline table deterministically hits the skipped branch. Added an invariant assertion on detailed.skipped.length.

R17-3 #11: printReport within-stream order tests now compare findLastIndex(earlier-group) vs findIndex(later-group). findIndex-only compared first-match only, which would pass even with interleaving. Fixture includes 2 OK + 2 SKIP (and 2 WARN + 2 FAIL) so the stronger assertion has teeth.

R17-3 #5: EACCES tests' silent `return;` on root replaced with `it.skipIf(isRoot)` at declaration time. The runtime 'filesystem does not enforce chmod' branch now emits a console.warn so the skip is visible in test output rather than a silent green.

R17-3 #6: Added isMainPath catch-branch test. vi.spyOn(path, 'resolve') throws once; asserts result is false, process.exitCode === EXIT_INTERNAL (2), and stderr log contains '[isMainPath] path.resolve failed'. Previously this branch had no coverage — a bare catch {} regression would pass all existing tests.
jpr5 added a commit that referenced this pull request Apr 18, 2026
R19-5 #3: Report interface had mutable string[] fields, inviting
drive-by mutation at read sites. Mark each bucket readonly string[]
and introduce a narrow ReportBuilder shape used only while building
the report in validateAll. Consumers of the returned Report see a
readonly view. Full PackageIssue tagged-union migration deferred —
noted inline — as it is a larger refactor without correctness impact.
shaneholloman pushed a commit to shaneholloman/copilotkit that referenced this pull request Apr 21, 2026
…te integration slug; sort-ordered preview selection

- Extract findFrameworksWithCell into @/lib/docs-render so the docs
  catch-all and framework-scoped catch-all share one implementation
  instead of carrying a near-identical local copy in each (finding CopilotKit#3).
- Validate /docs/integrations/<slug> against the registry with
  notFound() when the slug is unknown. Previously a crafted URL like
  /docs/integrations/fake-framework silently fell through to an empty
  nav tree, indistinguishable from a valid integration with no scoped
  content (finding CopilotKit#4).
- Sort integrations by sort_order then slug before picking the
  animated preview URL. Registry iteration order alone isn't
  deterministic w.r.t. the visual priority the docs UI shows
  everywhere else, so the preview now matches (finding CopilotKit#5).
shaneholloman pushed a commit to shaneholloman/copilotkit that referenced this pull request Apr 21, 2026
…null-alt filter, registry-gated landing cards

- Reject RESERVED_ROUTE_SLUGS at the handler as defense-in-depth.
  Next.js already prefers exact-match top-level routes over this
  catch-all, so /docs, /ag-ui, etc. never reach here under normal
  routing — but if the registry ever ships an integration whose slug
  collides with a reserved segment, the handler now short-circuits
  with notFound() rather than rendering garbage (finding CopilotKit#6).
- Import the shared findFrameworksWithCell helper instead of a
  duplicated local copy (finding CopilotKit#3 follow-through).
- Filter out unresolved alternative-framework slugs BEFORE mapping
  to React fragments so the ", " separator aligns with the final
  rendered count. The pre-filter index previously emitted stray
  commas when an entry dropped to null mid-sequence (finding CopilotKit#7).
- FrameworkLandingPage's four hardcoded LandingCards are now gated by
  registry integration.features presence: strands (no HITL support)
  no longer shows a dead "Human-in-the-Loop" card. The card
  definitions are hoisted into a module-level constant with a TODO
  pointing at the eventual feature-id → doc-slug mapping
  (finding CopilotKit#8).
- Declare export const dynamicParams = true explicitly so a future
  migration to output: "export" fails loudly here (under static
  export dynamicParams must be false) rather than silently 404ing
  every /<framework>/<slug> URL (finding CopilotKit#9).
AlemTuzlak added a commit that referenced this pull request Apr 22, 2026
## CI hygiene fixes

Four direct-fix items surfaced during the 2026-04-16 QA/E2E blitz,
bundled as one PR with one commit per fix:

1. **`test_unit.yml` paths-ignore** — add `showcase/**` +
`sdk-python/**` (prevents spurious TS unit matrix runs on showcase-only
or sdk-python-only PRs). `sdk-python-old/**` was mentioned in the plan
but doesn't exist on main; only the two existing dirs are added.
2. **`test_doc-examples.yml`** — scope PR trigger to `branches: [main]`
(matches convention of other workflows).
3. **`e2e_dojo.yml`** — symmetric `.changeset` path filter on push+PR
(was asymmetric — already in the `dorny/paths-filter` step's `ts:` list,
so this aligns the trigger).
4. **`starter-smoke.yml`** — rename internal job id (`starter-smoke` →
`smoke-starter`) and artifact name pattern (cosmetic; matches the new
`test_<layer>-<target>` / `smoke-<layer>` naming convention; no external
consumers).

### Fix skipped

**`showcase_smoke-monitor.yml` slug normalization** (item #10 in the
Notion page) — inspecting the file, it already uses the
`showcase/packages/` slug convention (`ms-agent-python`,
`ms-agent-dotnet`, `strands`). The apparent inconsistency is actually in
`starter-smoke.yml`, whose matrix keys must stay as
`ms-agent-framework-*` / `strands-python` because they are literal
directory names in `examples/integrations/` (used as `working-directory:
examples/integrations/${{ matrix.starter }}`). So there is no actionable
change here — the two files use different slug conventions *by
necessity*, because they target different directories (deployed
`showcase/packages/*` vs. local `examples/integrations/*`). Flagging for
the author of the blitz notes in case the actual concern was something
else.

Refs: [Bugs Found During
Blitz](https://www.notion.so/3443aa381852812fb595c5118dd68818) items #3,
#8, #9, #12.
jenningsloy318 pushed a commit to JMaiGC/CopilotKit that referenced this pull request May 8, 2026
PILL_GRADIENT_HINTS contained naked hex prefixes (e.g. "#0", "CopilotKit#1",
"CopilotKit#2", "#ff", "#fb", "CopilotKit#3"-"CopilotKit#9") that accidentally cross-matched
across families — cosmic's #1e3a8a matches forest's "CopilotKit#1", so a
regression returning the same gradient for every pill could have
silently passed.

Drop ALL naked-hex prefix hints. Keep only color-name keywords:
  - sunset: sunset, orange, red, rose, pink, amber, coral, peach
  - forest: forest, green, emerald, lime, olive, teal
  - cosmic: cosmic, space, navy, magenta, purple, violet, indigo,
            fuchsia
If full-hex matching is ever needed, use full 6-digit codes from
the actual fixture rather than 1-2 character prefixes.

Also fix the broken "background did not change off baseline" test:
the previous assertion built a baseline-only page mock and then
discarded it via `void page`. Replaced with a fake-timer-driven
invocation that actually triggers the timeout branch, plus a
separate test for the wrong-family path.
fengpiao-debug pushed a commit to fengpiao-debug/CopilotKit that referenced this pull request Jun 17, 2026
…8.37/-2.96% on 3 fixtures

crewai-crews/ms-agent-python/pydantic-ai catchall AAPL entries still carried stale $189.42/up 1.27% narration and toolCall args lacking price_usd/change_pct. Round 1 CR finding CopilotKit#3 was identified but never given a fix agent. Brought all 3 to canonical shape matching built-in-agent (A5) and csdkts narration (A6): price_usd=338.37, change_pct=-2.96, narration 'AAPL is trading at $338.37, down 2.96% on the day — rendered through the custom wildcard catchall.'

(cherry picked from commit df84657310451500278d0b3d0125c9c490042d2b)
huangyingting pushed a commit to repomesh/CopilotKit that referenced this pull request Jun 18, 2026
…command, and lsof-graceful inspector

- Update 12 slot-0-assumption tests for slot-0 reservation contract
- Add lsof stub and foundation smoke for isolate.bats
- Tests CopilotKit#1-CopilotKit#3: slot pinning behavior
- Tests CopilotKit#4-CopilotKit#7: port-probe and stale-reap behavior
- Tests CopilotKit#8-CopilotKit#10: slot state, slots subcommand, concurrent claim
- New test for _slot_state ports=? when lsof unavailable
AlemTuzlak added a commit that referenced this pull request Jul 6, 2026
…rwarded inbound headers (#5782)

## Problem

When a self-hosted v2 `CopilotRuntime` is configured with a server-side
agent (an `@ag-ui/client` `HttpAgent` with static `headers` for
service-to-service auth), the runtime forwards inbound
`authorization`/`x-*` request headers onto the agent's outgoing call
**and lets them override the headers the server configured** — silently
breaking service-to-service auth to a secured backend (e.g. a private
Cloud Run agent behind IAM).

`Fixes #5712`

## Root cause


`packages/runtime/src/v2/runtime/handlers/shared/agent-utils.ts:125-128`
merged forwarded inbound headers **last**, so they won on collision:

```ts
agent.headers = {
  ...agent.headers,                      // server-configured
  ...extractForwardableHeaders(request), // inbound — overrode the above
};
```

There are actually **two** failure modes:

1. **Same-case collision** — inbound `authorization` overwrites a server
`authorization` (last-write-wins).
2. **Case-mismatch collision** — `extractForwardableHeaders` lowercases
inbound keys (`authorization`), while the server typically configures
canonical casing (`Authorization`). A plain spread treats those as
*distinct* keys and emits **both** — which undici downstream comma-joins
into a single invalid `"Bearer A, Bearer B"` ("multiple JWTs") value.
Flipping the spread order alone does **not** fix this case.

## Fix

In `agent-utils.ts`, make server-configured `agent.headers`
authoritative on collision, matched **case-insensitively**: drop any
forwarded inbound header whose name (case-insensitively) is already set
on the agent, and let non-colliding inbound headers pass through
unchanged. This preserves the existing forward-for-auth behavior for
headers the server does *not* set, while guaranteeing a server-set token
is never overridden or duplicated.

The merge logic lives in a shared
`mergeForwardableHeaders(serverHeaders, request)` helper in
`packages/runtime/src/v2/runtime/handlers/header-utils.ts` so the
precedence semantics are defined in exactly one place.

### Scope note

This is the conservative precedence + case-insensitive-dedup fix (the
issue's suggested fix #1). I did **not** tighten the default allowlist
to drop hop-by-hop/platform `x-*` headers (`x-serverless-*`,
`x-forwarded-*`, …) or add an opt-out — those alter existing forwarding
behavior and are worth a separate, deliberate change. The precedence fix
alone resolves the reported breakage (the server-set token now wins
regardless of what the platform injects on a colliding header name).

A documented workaround already exists for users on released versions:
pass a custom `fetch` to the `HttpAgent` that builds outgoing headers
from scratch (it runs after `configureAgentForRequest` and survives the
per-request `agent.clone()`).

## Red-green proof (the real fix — `/run` path)

The load-bearing assertion: there must be exactly **one** authorization
header carrying the **server** value.

### RED (fix stashed, against unmodified `agent-utils.ts`)

```
 ❯ src/v2/runtime/__tests__/agent-header-precedence.test.ts (2 tests | 1 failed)
   × configureAgentForRequest — header precedence (#5712) > server-configured agent headers win over a colliding inbound header
AssertionError: expected [ 'Authorization', 'authorization' ] to have a length of 1 but got 2
     81|     expect(authKeys).toHaveLength(1);
 Test Files  1 failed (1)
      Tests  1 failed | 1 passed (2)
```

The pre-existing `agent-utils-header-forwarding.test.ts` also failed,
because it explicitly encoded the buggy behavior
(`expect(...["x-aimock-context"]).toBe("new-context")` — inbound
winning):

```
 FAIL  src/v2/runtime/__tests__/agent-utils-header-forwarding.test.ts > ... > request forwardable headers override matching pre-existing agent headers
AssertionError: expected 'old-context' to be 'new-context'
```

### GREEN (fix applied)

```
 ✓ src/v2/runtime/__tests__/agent-header-precedence.test.ts (2 tests) 2ms
 ✓ src/v2/runtime/__tests__/agent-utils-header-forwarding.test.ts (8 tests) 3ms
 Test Files  2 passed (2)
      Tests  10 passed (10)
```

The colliding test (`agent-utils-header-forwarding.test.ts`) was updated
from asserting the old bug to asserting corrected precedence + a new
case-insensitive-dedup guard. The non-colliding-forward test is retained
unchanged as a regression guard.

## Quality gates

```
NX  Successfully ran target check-types for project @copilotkit/runtime
NX  Successfully ran target test for project @copilotkit/runtime  — Test Files 113 passed (113), Tests 1576 passed (1576)
```

---

## `/connect`-path change — forward-looking plumbing, inert today

The original issue and a prior eval flagged the same forwarding pattern
at `handlers/sse/connect.ts`. To keep the two paths' merge semantics
consistent, the `/connect` path now builds the same server-wins merged
headers (via the shared `mergeForwardableHeaders` helper) and passes
them into `runner.connect()`.

**This is not an active auth fix, and it is not red-green-proven as one
— because there is no live bug to fix on the connect path today.** No
shipped runner consumes the `headers` field of
`AgentRunnerConnectRequest`: the in-memory, intelligence, telemetry, and
sqlite runners all destructure only `threadId` from the connect request
and ignore `headers` entirely. Connect is a thread replay/reconnect, not
a fresh outgoing agent call. So whatever headers we pass into
`runner.connect()` are dropped on the floor by every runner that ships.

What this change actually does:

- Threads the per-request agent clone through `handle-connect.ts →
handleSseConnect` so the connect path *has access to* the
server-configured `agent.headers` (it previously did not).
- Passes `mergeForwardableHeaders(agent?.headers, request)` into
`runner.connect()` — the correct, server-wins argument **shape** for a
future outbound-connecting runner that *would* consume connect-path
headers.
- Rewrites the comments/JSDoc on this path to say this plainly, rather
than implying an active auth fix. It also documents that the
connect-site `cloneAgentForRequest` call is the sole `agentId`-existence
guard (the intelligence branch never re-validates the id), and documents
`cloneAgentForRequest`'s `AbstractAgent | Response` (404) dual-return
contract that both callers depend on.

The real outbound header forwarding — the thing that fixes #5712 — is
the `/run` path's `agent.headers` mutation described above. The connect
change is staged plumbing so that if/when a runner starts honoring
connect-path headers, it inherits the same server-wins precedence
without a second fix.

### Tests on the `/connect` path

The connect tests assert the *merge shape* that reaches
`runner.connect()` (server value wins on collision, exactly one
`authorization` key, non-colliding `x-*` still forwards) and that the
agent-undefined case (no server `agent.headers`) degrades to forwarding
allowlisted inbound headers only and does not crash. These verify the
argument we construct is correctly shaped — not that any shipped runner
consumes it.

## Files

- `packages/runtime/src/v2/runtime/handlers/header-utils.ts` — shared
`mergeForwardableHeaders` helper (case-insensitive, server-wins).
- `packages/runtime/src/v2/runtime/handlers/shared/agent-utils.ts` —
`/run` path uses the helper so server headers win on collision (**the
real fix**).
- `packages/runtime/src/v2/runtime/handlers/sse/connect.ts` — `/connect`
path uses the helper; forward-looking plumbing, inert until a runner
consumes connect-path headers.
- `packages/runtime/src/v2/runtime/handlers/handle-connect.ts` — threads
the per-request agent clone into `handleSseConnect`.
-
`packages/runtime/src/v2/runtime/__tests__/agent-header-precedence.test.ts`
— `/run` regression test exercising the real `configureAgentForRequest`
surface with a real `HttpAgent`.
-
`packages/runtime/src/v2/runtime/__tests__/agent-utils-header-forwarding.test.ts`
— updated the test that encoded the old (buggy) precedence; added a
case-mismatch dedup guard.
-
`packages/runtime/src/v2/runtime/handlers/sse/__tests__/sse-connect-agent-id.test.ts`
— connect-path merge-shape + agent-undefined coverage.

### Notes

- A documented `@ag-ui/client` `HttpAgent` `fetch` workaround already
exists for attaching service-to-service auth the runtime can't override
(see the issue). This change makes the workaround unnecessary for the
`/run` precedence case.
- Conservative scope: this is the **precedence flip on `/run`** plus
forward-looking connect plumbing. Tightening the default allowlist
(dropping hop-by-hop / platform `x-serverless-*`, `x-forwarded-*`,
`x-cloud-trace-context`, …) and an opt-out switch — issue suggestions
#2/#3 — are intentionally left as a follow-up to keep the
security-policy change minimal.
jpr5 added a commit that referenced this pull request Jul 8, 2026
…wrapped-PID kill through guarded tree-kill

CLASS 1 (guard silently disabled by a bad numeric override): add a reusable
_require_int validator and run it at startup over EVERY operator-overridable
numeric knob in both entrypoints (size threshold/interval, startup grace,
health-probe interval, strike limit). A non-integer/empty override now WARNs
and falls back to the documented default instead of breaking a sleep/loop/
arithmetic test. Closes instance #3 (LANGGRAPH_SIZE_CHECK_INTERVAL='60s'
killing the size-monitor loop on its first iteration).

CLASS 2 (wrapped-PID orphan + kill-0 footgun): route the cleanup() NEXTJS_PID
kill through _kill_agent_tree (it is process-sub-wrapped like the agent, so a
bare kill orphaned the real Next.js node server holding $PORT across redeploy).
Harden _kill_agent_tree and _agent_descendants to refuse a PID that is empty,
non-numeric, 0, or 1 (fail closed), making kill -9 0 / kill -9 1 structurally
impossible. Remove the ${AGENT_PID:-0} sentinel in the --check-size-once seam;
skip with a warning when AGENT_PID is unset instead of defaulting to 0.

Shared helper code kept byte-identical between the two entrypoints.
tylerslaton added a commit that referenced this pull request Jul 9, 2026
…ard tests

CR-loop confirmation-round #3 findings:

- validator: a `types` condition now "wins" a resolution mode only when it
  actually covers that mode (new `typesCoversMode`). A partial object `types`
  (e.g. only `import`) no longer silently covers `require` — resolution falls
  through to the sibling, catching a real #3324 shape the checker previously
  missed. normalizeExports doc + a "read or parse" message tidied.
- helper: idempotency now keys on the FIRST condition being `types` (its own
  output shape) rather than mere presence, so a hand-authored `types`-last
  entry is normalized instead of passed through — keeping helper output
  consistent with what the validator accepts. JSDoc corrected (acts on every
  condition target, requires a subpath map, only ADDS a missing `types`).
- tests: made the runtime-only test discriminating (a `browser`-only target
  must not be flagged — the prior fixture couldn't catch a regression);
  exercised `node`; added partial/well-formed object-`types`, top-level
  fallback array, and types-last normalization cases.

Call sites: typesCoversMode (new internal, called by walk); walk/withTypes
signatures unchanged; isActiveCondition now also used by typesCoversMode.

32 tests pass; validator typechecks; real 25-package validate:exports exits 0;
native-loader react-core build unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
tylerslaton added a commit that referenced this pull request Jul 10, 2026
…ard tests

CR-loop confirmation-round #3 findings:

- validator: a `types` condition now "wins" a resolution mode only when it
  actually covers that mode (new `typesCoversMode`). A partial object `types`
  (e.g. only `import`) no longer silently covers `require` — resolution falls
  through to the sibling, catching a real #3324 shape the checker previously
  missed. normalizeExports doc + a "read or parse" message tidied.
- helper: idempotency now keys on the FIRST condition being `types` (its own
  output shape) rather than mere presence, so a hand-authored `types`-last
  entry is normalized instead of passed through — keeping helper output
  consistent with what the validator accepts. JSDoc corrected (acts on every
  condition target, requires a subpath map, only ADDS a missing `types`).
- tests: made the runtime-only test discriminating (a `browser`-only target
  must not be flagged — the prior fixture couldn't catch a regression);
  exercised `node`; added partial/well-formed object-`types`, top-level
  fallback array, and types-last normalization cases.

Call sites: typesCoversMode (new internal, called by walk); walk/withTypes
signatures unchanged; isActiveCondition now also used by typesCoversMode.

32 tests pass; validator typechecks; real 25-package validate:exports exits 0;
native-loader react-core build unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
tylerslaton added a commit that referenced this pull request Jul 18, 2026
#6035)

## What

Follow-up nit from [PR
#5969](#5969) review
([OSS-488](https://linear.app/copilotkit/issue/OSS-488)). Fixes the
`getMessages` JSDoc in
`packages/channels-intelligence/src/intelligence-adapter.ts`, which
oversold image support.

The comment cited *"what was in the image"* as a `read_thread` use case,
but image/file parts contribute **no text** in this mapping —
`read_thread` is text-only by design. Image *content* reaches the model
only via `conversationStore`'s seeding of `agent.messages`. The comment
now says so explicitly instead of implying `read_thread` can see image
content.

Comment-only change — no runtime/API behavior change, so no changeset.

## Scope of OSS-488

The ticket listed three nits; this PR addresses the one still
actionable:

- **#1 (double-space when joining content parts)** — ✅ already resolved
on `main` (the `.filter(Boolean).join(" ")` fix + updated test landed
via the OSS-476 CR round). Nothing to do.
- **#2 (JSDoc oversells image support)** — ✅ **this PR**.
- **#3 (duplicate `getHistory` fetch per turn)** — intentionally
**deferred**. A per-turn memo would need turn-scoped caching with a
clear-on-turn-start hook; without one it risks serving stale history — a
correctness regression on something the ticket itself rates "acceptable
for an on-demand tool." Not worth it here.

The **known limitation** (speakers collapse to `user`/`bot` because
upstream `AgentMessage` carries no names) is unchanged and not
actionable at this layer.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
BenTaylorDev added a commit that referenced this pull request Jul 20, 2026
## What does this PR do?

Fixes a Vue `DataCloneError` that occurred when uploaded attachment
sources crossed the `structuredClone` boundary in core. Vue’s deep
`ref()` conversion wrapped nested attachment sources in reactive
proxies; `useAttachments` now keeps the attachment container shallow
with `shallowRef()`, preserving externally supplied sources as raw
cloneable values before they reach AG-UI/core payloads.

The change is intentionally Vue-only: core and React are untouched
because the defect is caused by Vue’s reactivity behavior at the
framework boundary. Focused regressions cover both the attachment hook
and `CopilotChat` submission path, including non-reactivity and
successful `structuredClone` behavior.

## Related PRs and Issues

- [CopilotKit issue
#3](enekesabel#3)

## Verification

- `pnpm nx run @copilotkit/vue:check-types` — passed.
- `pnpm nx run @copilotkit/vue:test --
src/v2/hooks/__tests__/use-attachments.test.ts
src/v2/components/chat/__tests__/CopilotChat.attachments.test.ts` —
passed, 18 tests in 2 files.
- `pnpm nx run @copilotkit/vue:build` — passed.
- Pre-commit package gate (`test-and-check-packages`) — passed: 1073
tests, publint, and attw.
- `pnpm nx run @copilotkit/vue:lint` — remains blocked by 171
pre-existing errors across unrelated Vue files; no lint errors were
introduced in the changed files.
- `git diff --check upstream/main...HEAD` — passed.

## Scope and exclusions

- Changed files are limited to
`packages/vue/src/v2/hooks/use-attachments.ts`, its focused hook and
`CopilotChat` tests, and the related `packages/vue/PARITY.md` and
`packages/vue/AGENTS.md` guidance.
- No core, React, workflow, or package-wide lint cleanup is included.
- The `PARITY.md` change removes accidental table-format churn and
retains only the meaningful attachment parity note.

## Checklist

- [x] I have read the [Contribution
Guide](https://github.com/CopilotKit/CopilotKit/blob/main/CONTRIBUTING.md)
- [x] If the PR changes or adds functionality, I have updated the
relevant documentation
- [x] "Allow edits by maintainers" is checked (lets us help iterate on
your PR directly — faster turnaround for everyone)
copilotkit-qa-bot Bot pushed a commit that referenced this pull request Jul 22, 2026
…e to LLM

SECURITY: All useAgentContext values are sent to LLM provider

The CopilotKitMiddleware JSON-serializes ALL context and injects it as
a SystemMessage. This means auth tokens appear in provider logs/traces
and can be referenced by the LLM.

Changes:
- Added prominent security callouts in configurable.mdx and auth.mdx
- Renamed 'authToken' examples to 'demoToken' with explicit warnings
- Added guidance to use secure headers/env vars for production auth
- Clarified these patterns are for demos/prototypes only

For production: use LangGraph Platform auth or secure HTTP headers.

Addresses review blocker #3 (FAC-121).
davidmckayv added a commit that referenced this pull request Jul 23, 2026
…k PDF Q2 report

Fixes three demo-pill defects surfaced in review:

- "What's on my screen?": the agent refused ("I can't inspect the live
  screen"). Add a SCREEN AWARENESS rule so it treats its context (current
  page + live cards/policies/transactions) as its screen view and answers
  confidently, citing the actual on-screen figures.

- "show the tool calls" (#6 Q2 report, #7 favorite food): add a wildcard
  ("*") renderToolCalls chip that renders a visible "tool . <label>" pill for
  every tool call with no richer renderer of its own (recall_memory,
  save_memory, createReport, render_report, ...). MCP-namespaced names map to
  friendly labels.

- Q2 report (#6): the suggestion path drops attachments, so the report never
  saw the PDF. A custom suggestionView slot (demo-suggestions.tsx) takes over
  pill clicks: "Prep the Q2 report" drives the real composer (stage invoice ->
  type -> send) so the PDF rides as a real attachment chip and the run
  completes cleanly (a hand-rolled runAgent left createReport's result
  dangling and Intelligence failed the run). gpt-5.4 reads the invoice and
  folds its line items into the filed report + charts via createReport
  additions (Spend Breakdown -> Marketing 96%).

- "Change my card PIN" (#3): the slot navigates to /?operation=change-pin to
  open the app's own PIN dialog instead of routing PIN entry through the agent
  pane.

Extract the invoice-staging helper (attach-invoice.ts) shared by the header
paperclip button and the Q2 pill. Includes the previously-uncommitted report
additions plumbing (data.ts, reports route, report-tool, reports-view).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
mxmzb added a commit that referenced this pull request Aug 12, 2026
…wave slots could not reach

Comment-only, no behaviour change. Each of these sat OUTSIDE the boundary of the
slot whose work falsified it, so each described the tree as it was mid-migration.
All verified against the current tree before editing.

src/shell/skin-contract.ts
- `RuntimeProviders`: "airline needs neither, so omits it". Airline omits
  `RuntimeProviders` and DOES supply `useRuntimeProperties` — the two are
  SEPARABLE, and airline is now the worked example: one account holder, no
  switcher, so its hook reads no context and returns a frozen module constant. Do
  not mount an empty provider for symmetry.
- `useData`: "Omit when a skin has no shell-managed data (banking …)". Every skin
  omits it now; documented with the grep, plus WHY the field is kept (the shape is
  legitimate, it just has no worked example left).
- `CanvasSurface`: the "omit if the skin has no report canvas" branch is currently
  unexercised — every shipped skin has one.

src/shell/agent-registry.ts
- The logistics entry said it ships "neither `intelligence/seed-memories.ts` nor
  `intelligence/forget-memories.ts`" and is "identity plumbing only — do NOT read
  it as a durable-memory demo". It ships both (`ls src/skins/*/intelligence/`), and
  its `dev/reset` sweeps and re-seeds through them. Corrected, with the same
  properties-forwarding caveat the other five entries carry, and a note that
  "expensive half built, cheap half skipped" was its state for two releases.

src/skins/keel/data/types.ts
- The `THE REST SUBSTRATE` banner said the two substrates are "deliberately not
  merged yet", that `useKeelData` "holds runs in `useState` and ticks them on a
  900 ms interval", and that "the pages still read it through `useSkinData`". All
  three are false: one substrate, one clock, `useSkinData` returns undefined.
  Rewritten to name the server-settled read (`settle-runs.ts`, called by both
  `GET /ledger` and `GET /runs/[runId]`) and to record WHY the deleted client
  ticker was a defect rather than a design choice — it was a second clock that
  painted progress the server never heard of, which the next re-read after any
  write silently rewound.
- The `KeelData` interface header claimed to be "the interface every page,
  component, and tool codes against". It is not referenced by any code at all
  (`grep -rn KeelData src` returns only comments). Marked HISTORICAL, with a
  do-not-add-a-consumer note. NOT deleted: it is a doc pass, several comments
  across the skin describe the migration in terms of this shape, and removing an
  exported type is a code change for a separate commit. Flagged as a follow-up.

src/skins/keel/data/store.ts
- "it does not advance them on a timer, because the ticker lives in `useKeelData`
  on the client. Whichever slot migrates that hook has to decide where the ticker
  ends up" — decided: the server is the only clock now.

src/skins/keel/data/beat-map.md
- Header: "Keel today is `useKeelData`, an in-memory `useState` store, and it hits
  about one beat." Marked BUILT and reframed as the design record.
- Risk #2 (the two-substrates/ticker question, correctly called "the biggest single
  risk in the migration") marked RESOLVED, with the answer (move the clock, do not
  relocate the ticker) and the generalised lesson.

src/skins/airline/data/beat-map.md
- Header: the tools/prompt/pages/pills were "later slots". All landed.
- § "What this slot did NOT build": every row of the deferral table has shipped.
  Kept as the retrofit record — which is the most useful thing about it — with a
  third column saying where each landed, and the three flagged traps marked
  resolved (including "the reset route says memoryBeats: unarmed on purpose",
  which was removed in exactly the change that added the seed module, as
  instructed).

src/skins/airline/data/fare-waiver-codes.ts
- "⚠️ THE LINT GUARD DOES NOT COVER THIS SKIN YET." It does: both
  `src/skins/airline/tools.tsx` and `agent.ts` are in `withheldGateVocabulary`'s
  `files` glob. Also dropped its "COUNT the selectors" instruction (that count has
  rotted twice) in favour of the resolved-selector table in
  `skins-config.test.ts`, and spelled out that a green lint still leaves the three
  prose channels AND `waiverGround` — which matches no `*_CODES` pattern, so the
  rule cannot see it — as hand-review items.

src/skins/airline/tools.test.ts
- Header said `statusKeyedTerminalRender` "covers logistics only; airline's glob
  entry is a later slot's, so until it lands this file is the whole guard" and that
  `withheldGateVocabulary`'s glob "does not list airline yet either". Both globs
  list airline now. Also fixed "Three defect classes" over a list of five.

src/skins/keel/skin.tsx
- "exactly as it does for the four other REST-backed skins" → every skin; nothing
  sets `useData`.

src/proxy.ts
- "matching how the other three skins behave" → numeral-free. This was one of the
  two known-stale instances named in `skin-roster-docs.test.ts`'s header; that
  header is updated in the app-docs commit, and the remaining one
  (`e2e/inset-layout.spec.ts`'s hardcoded four-skin loop) is deliberately left —
  fixing it means adding assertions against skins the spec has never visited, which
  is a coverage change rather than a prose fix.

docs/teach-mode/README.md
- It correctly refuses to write the roster into prose, but its verified-by-role
  paragraph named only banking/commerce/logistics/people and its "so copy commerce
  or logistics" line named the only two skins with pinned replay behaviour. The
  `offerWorkflowRecording` grep now returns every registered skin, and
  `ls src/skins/*/teach-mode-directives.ts` — added as the mechanical
  discriminator for role #3 — returns four. Also: "logistics and commerce both"
  skip project-scoped rows in `forget-memories.ts` is now every skin but banking,
  replaced with the grep that proves it.

Does this make anything in .claude/skills/reskin/ stale? No — the reverse. The
preceding commit updated the skill for exactly these facts, and these comments were
brought into line with it. Checked: `grep -rn "useKeelData\|use-data\|in-memory"
.claude/skills/reskin/` names no path or symbol that no longer exists.

Verified: pnpm lint, pnpm exec tsc --noEmit, pnpm test:unit (197 files / 2227
tests), pnpm build — all green.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
jpr5 added a commit that referenced this pull request Aug 12, 2026
…, stop saturated workers claiming (#6333)

> **This PR carries three changes to the same prod incident.** Change 1
fixes
> the PID leak itself; changes 2 and 3 fix the two reasons the leak was
able to
> starve the fleet unannounced. Each has its own RED → GREEN below.
>
> | # | Commit | What it fixes |
> |---|---|---|
> | 1 | `e66fb1af13` | **The leak.** No PID-1 reaper, so crashed
chromium grandchildren become permanent zombies holding cgroup PID
slots. |
> | 2 | `7f28e9bd39` | **Nothing alarmed.** The worker heartbeats its
cgroup PID gauges and no non-test code read them. |
> | 3 | `63ef4081c2` | **Saturated workers kept claiming.** The claim
gate only checked free browser-context slots, so a worker at 1000/1000
PIDs won jobs it could not run and burned each to a 600000ms abort. |

---

# CHANGE 1 — the leak (tini as PID 1)

## The bug

`harness-workers` has **no PID-1 zombie reaper**, so it leaks cgroup PID
slots until it cannot launch a browser.

libuv's `SIGCHLD` handler only `waitpid()`s the pids **Node itself
spawned**. Playwright spawns the chromium *browser* process (reaped
fine), but that browser's **zygote/renderer/GPU children are
grandchildren**. When a browser process dies — prod's `Target crashed`
path, or a pool self-heal relaunch — those grandchildren are re-parented
onto PID 1 and exit. Node-as-PID-1 never waits on them, so each becomes
a permanent `<defunct>` still holding a cgroup PID slot.

Prod, on a single container up 6d22h: `zombieCount` 70 → **757**,
`cgroupPidsCurrent` 286 → **1000/1000**. Once saturated, probes could
not launch browsers (`Target crashed`, `browserContext.newPage: … has
been closed`, `feature exceeded 300000ms wall-clock`) and **295 of 414
red prod d6 cells went `abort`, fleet-wide across ~20 slugs.**

This Dockerfile already documented the outage mode in a 40-line `FIX #3`
block — but **both of its stated mitigations are demand-side**
(`BROWSER_POOL_MAX_CONTEXTS` 40→24, resource-gauge warning logs). Those
cap the *peak* of `pids.current`. They cannot stop a *monotonic* leak,
and prod died of a monotonic leak. `resource-gauges.ts` only ever
**measured** zombies (`if (s.state === "Z") zombieCount += 1`); nothing
reaped them.

## The change

One file, +59/-3. `tini` as PID 1.

```dockerfile
RUN node ./node_modules/playwright/cli.js install --with-deps chromium \
 && apt-get install -y --no-install-recommends tini \
 && /usr/bin/tini --version \
 && rm -rf /var/lib/apt/lists/*
…
ENTRYPOINT ["/usr/bin/tini", "--"]
CMD ["/bin/bash", "-c", "ulimit -u $(ulimit -Hu) 2>/dev/null || true; exec node dist/orchestrator.js"]
```

Why this form:

- **`tini` baked into the image, not Docker `--init`** — `--init` is a
*runtime* flag and Railway does not expose it, the same reason
`pids.max` isn't settable from here (already documented in this file).
- **Not an in-process reaper** — Node has no `waitpid` binding, so an
application `SIGCHLD` handler would need a native addon. This is the
platform's job.
- **Rides the existing apt layer** — playwright's `--with-deps` just ran
`apt-get update`, so this costs one ~267KB package download instead of a
second index refresh. The `tini --version` call is a build-time
assertion on the path baked into `ENTRYPOINT`: if a future Debian moves
the binary, the **build** fails rather than the container failing to
start in prod.
- **No `-g`** — tini's process-group broadcast would signal the live
chromium pool alongside node and pre-empt `orchestrator.ts`'s
`process.once("SIGTERM", drainAndExit)`. Without it, delivery is
byte-identical to today: exactly one process gets the signal.
- **Exec form, `exec` kept in CMD** — tini really is PID 1 and really
receives Railway's SIGTERM; node is tini's direct child with no bash
lingering in the tree.

No existing convention to match: `grep` for `tini`/`dumb-init`/`--init`
across every Dockerfile in the repo returns zero hits. Nothing in the
repo asserts on this image's `CMD`/`ENTRYPOINT`, and nothing outside the
CI build step `docker run`s it, so adding an `ENTRYPOINT` breaks no
consumer.

---

# RED → GREEN

Real container, real chromium, real zombies. **Identical argv for
both**; only the image differs, and the image supplies PID 1:

```
docker run --rm --pids-limit 1000 -e REPRO_CYCLES=230 \
  -v <repro>:/repro:ro <image> /bin/bash -c "exec node /repro/zombie-repro.mjs"
```

`--pids-limit 1000` mirrors Railway's platform-fixed ceiling. Each cycle
launches chromium with the exact args `browser-pool.ts` uses
(`headless`, `--no-sandbox`, `--disable-dev-shm-usage`), opens a
context+page, then **SIGKILLs the browser process** — prod's `Target
crashed` path, orphaning its children onto PID 1.

**Measurement is container-wide on purpose.** The harness's own
`sampleResourceGauges()` walks the tree from `process.pid`; under a real
init the orphans re-parent to the *init*, not to node, so a node-rooted
walk would report zero zombies **whether or not they were reaped** — a
vacuous GREEN. Counting every state-`Z` process in `/proc` plus the
cgroup counter is blind to which process is PID 1, so it is honest in
both directions.

## RED (unmodified `main`, `pid1=node`)

20 cycles — exactly **+5 permanent zombies per crashed browser**:

```
baseline zombieCount=0 procCount=1 threadCount=7 cgroupPidsCurrent=7 cgroupPidsMax=1000 selfPid=1 pid1=node
  PID  PPID S THR COMMAND
    1     0 R   7 node
cycle=1 pre-kill zombieCount=0 procCount=7 threadCount=76 cgroupPidsCurrent=76 cgroupPidsMax=1000 selfPid=1 pid1=node
cycle=1 zombieCount=5 procCount=6 threadCount=16 cgroupPidsCurrent=16 cgroupPidsMax=1000 selfPid=1 pid1=node
cycle=2 zombieCount=10 procCount=11 threadCount=21 cgroupPidsCurrent=21 cgroupPidsMax=1000 selfPid=1 pid1=node
cycle=3 zombieCount=15 procCount=16 threadCount=26 cgroupPidsCurrent=26 cgroupPidsMax=1000 selfPid=1 pid1=node
…
cycle=20 zombieCount=100 procCount=101 threadCount=111 cgroupPidsCurrent=111 cgroupPidsMax=1000 selfPid=1 pid1=node
final    zombieCount=100 procCount=101 threadCount=111 cgroupPidsCurrent=111 cgroupPidsMax=1000 selfPid=1 pid1=node
SUMMARY cycles=20 zombiesBefore=0 zombiesAfter=100 pidsBefore=7 pidsAfter=111 launchFailure=none
```

The leaked processes, verbatim from the final `/proc` table — all
`ppid=1`, all `Z`:

```
   21     1 Z   1 headless_shell <defunct>
   22     1 Z   1 headless_shell <defunct>
   36     1 Z   1 headless_shell <defunct>
   61     1 Z   1 headless_shell <defunct>
   77     1 Z   1 headless_shell <defunct>
   87     1 Z   1 headless_shell <defunct>
   88     1 Z   1 headless_shell <defunct>
  104     1 Z   1 headless_shell <defunct>
```

`cgroupPidsCurrent` after each cycle never returns to 7 — it is `7 +
5×cycles`. A monotonic ratchet, the same curve prod walked over 7 days.

### RED, driven to saturation (started before the Dockerfile was
touched)

```
baseline  zombieCount=0    cgroupPidsCurrent=7    /1000
cycle=25  zombieCount=125  cgroupPidsCurrent=136  /1000
cycle=50  zombieCount=250  cgroupPidsCurrent=261  /1000
cycle=75  zombieCount=375  cgroupPidsCurrent=386  /1000
cycle=100 zombieCount=500  cgroupPidsCurrent=511  /1000
cycle=125 zombieCount=625  cgroupPidsCurrent=636  /1000
cycle=150 zombieCount=750  cgroupPidsCurrent=761  /1000     ← prod's ~757 reproduced
cycle=175 zombieCount=875  cgroupPidsCurrent=886  /1000
cycle=184 pre-kill  zombieCount=915  cgroupPidsCurrent=993  /1000
cycle=185 pre-kill  zombieCount=920  cgroupPidsCurrent=996  /1000
cycle=185           zombieCount=925  cgroupPidsCurrent=936  /1000
   ← no further output. Cycle 186 never completed.
```

The run **wedged** at cycle 185 with no output for >12 minutes:
`chromium.launch()` could not get PIDs and never returned — it did not
even surface Playwright's 30s launch timeout, which is exactly why prod
shows 300s feature timeouts and 1200s run aborts instead of a clean
launch error. `docker ps`: `Up 17 minutes (unhealthy)`.

```
$ docker exec red-sat cat /sys/fs/cgroup/pids.current /sys/fs/cgroup/pids.max
1000
1000
```

And the errno-11 signature this Dockerfile's own comment names — the
container could no longer `fork()` at all:

```
$ docker exec red-sat /bin/bash -c 'for i in 1 2 3; do cat /proc/uptime; done'
/bin/bash: fork: retry: Resource temporarily unavailable
/bin/bash: fork: retry: Resource temporarily unavailable
/bin/bash: fork: retry: Resource temporarily unavailable
/bin/bash: fork: retry: Resource temporarily unavailable
/bin/bash: fork: Resource temporarily unavailable
```

That is the prod outage, end to end, in a local container.

## GREEN (this PR's image, `pid1=tini`) — same repro, same argv, 230
cycles

```
baseline zombieCount=0 procCount=2 threadCount=8 cgroupPidsCurrent=8 cgroupPidsMax=1000 selfPid=7 pid1=tini
  PID  PPID S THR COMMAND
    1     0 S   1 tini
    7     1 R   7 node
cycle=1   pre-kill zombieCount=0 procCount=8 threadCount=76 cgroupPidsCurrent=76 cgroupPidsMax=1000 selfPid=7 pid1=tini
cycle=1            zombieCount=0 procCount=2 threadCount=12 cgroupPidsCurrent=12 cgroupPidsMax=1000 selfPid=7 pid1=tini
cycle=50           zombieCount=0 procCount=2 threadCount=12 cgroupPidsCurrent=12 cgroupPidsMax=1000 selfPid=7 pid1=tini
cycle=100          zombieCount=0 procCount=2 threadCount=12 cgroupPidsCurrent=12 cgroupPidsMax=1000 selfPid=7 pid1=tini
cycle=150          zombieCount=0 procCount=2 threadCount=12 cgroupPidsCurrent=12 cgroupPidsMax=1000 selfPid=7 pid1=tini
cycle=200          zombieCount=0 procCount=2 threadCount=12 cgroupPidsCurrent=12 cgroupPidsMax=1000 selfPid=7 pid1=tini
cycle=230 pre-kill zombieCount=0 procCount=8 threadCount=77 cgroupPidsCurrent=77 cgroupPidsMax=1000 selfPid=7 pid1=tini
cycle=230          zombieCount=0 procCount=2 threadCount=12 cgroupPidsCurrent=12 cgroupPidsMax=1000 selfPid=7 pid1=tini
final              zombieCount=0 procCount=2 threadCount=12 cgroupPidsCurrent=12 cgroupPidsMax=1000 selfPid=7 pid1=tini
SUMMARY cycles=230 zombiesBefore=0 zombiesAfter=0 pidsBefore=8 pidsAfter=12 launchFailure=none
```

`procCount` returning to **2** (tini + node) after every single cycle is
the reap actually happening: the browser's 6 processes appear pre-kill
(`procCount=8`) and are fully gone post-kill.

|  | RED (`pid1=node`) | GREEN (`pid1=tini`) |
| --- | --- | --- |
| zombies after 20 cycles | 100 | **0** |
| zombies at cycle 185 | 925 | **0** |
| `pids.current` floor at cycle 185 | 936, peaking 996/1000 | **12** |
| reached cycle 230? | **no — wedged at 185** | yes |
| `chromium.launch()` | hangs; `fork: Resource temporarily unavailable`
| fine, `launchFailure=none` |
| leak per crashed browser | **+5** | **0** |

---

## Signals and non-zero exit still work

The prober's container must still self-restart on crash, so this was
proven, not assumed. `signal-child.mjs` installs the same
`process.once("SIGTERM", …)` shape `orchestrator.ts` uses; run on
**both** images:

```
--- GREEN (ENTRYPOINT tini, pid1=tini) ---
[showcase-harness:green MODE=term-graceful] exitCode=0
    CHILD mode=term-graceful pid=7 ppid=1
    CHILD ready — idling until signalled
    CHILD received SIGTERM at pid=7 — draining        ← tini FORWARDED it to node
[showcase-harness:green MODE=exit-42] exitCode=42     ← non-zero preserved
[showcase-harness:green MODE=abort]   exitCode=134    ← 128+6 (SIGABRT), non-zero
--- RED (no ENTRYPOINT, pid1=node) — baseline ---
[showcase-harness:red MODE=term-graceful] exitCode=0
    CHILD received SIGTERM at pid=1 — draining
[showcase-harness:red MODE=exit-42] exitCode=42
[showcase-harness:red MODE=abort]   exitCode=133
```

- **SIGTERM reaches node, not just tini** — the handler fires at
`pid=7`, so `docker stop`'s SIGTERM was forwarded into the process that
owns the graceful drain. `orchestrator.ts`'s
`drainControlPlaneAndExit("SIGTERM")` path is intact.
- **Non-zero exits survive** — `exit(42)` → container `42`; a crash
still exits non-zero, so Railway still restarts. The HEALTHCHECK
restart-on-sustained-503 behaviour this Dockerfile calls "THE INTENDED
OUTCOME" is untouched.
- **tini is strictly *more* correct here**: note RED's abort → **133**
vs GREEN's → **134**. A process running as PID 1 in a namespace has
default signal actions *ignored* by the kernel, so node-as-PID-1 was
distorting its own fatal-signal exit code (128+SIGTRAP instead of
128+SIGABRT). Both non-zero, so no regression — but the fixed image
reports crashes accurately.

## Cross-arch check

Local images are arm64; prod builds amd64. `tini` availability was
verified on amd64 explicitly rather than assumed — same path the
build-time assertion checks:

```
Package: tini
Architecture: amd64
Version: 0.19.0-1+b3
-rwxr-xr-x 1 root root 27792 Jun  6  2025 /usr/bin/tini
tini version 0.19.0
```

## Pre-push checks

| Check | Result |
| --- | --- |
| `docker buildx build -f showcase/harness/Dockerfile` (== CI's build
check) | **PASS**, both images |
| `nx run @copilotkit/showcase-harness:typecheck` | **PASS** |
| `nx run @copilotkit/showcase-harness:test:ci` | 3677 passed, 18
skipped, 1 failed — **environmental**, see below |
| commitlint | **PASS** |
| lefthook `pre-commit` + `commit-msg` | **PASS** |
| `git status` | clean |

The single failure is `d0-gone-predicate.test.ts > resolves the real
generated registry.json…`, failing on `ENOENT …
showcase/shell/src/data/registry.json`. That file is **gitignored and
generated at build time** — this Dockerfile's own comment says so, which
is why the image generates it via `generate-registry.ts`. Proven
environmental rather than assumed: generated the file, re-ran that exact
spec, **11/11 passed**. A Dockerfile-only diff cannot affect a vitest
run.

No formatter/linter covers this file: lefthook's `lint-fix` glob is
`*.{js,jsx,ts,tsx,mjs,cjs,md,css,yml,yaml,html,vue,py}`, and there is no
hadolint anywhere in CI.

## Not in this PR

- **This does not fix prod by itself.** Prod is digest-pinned and still
running the leaking container; it needs the live mitigation restart
(owned by a separate worker — **prod was not touched here**) and then a
promote to pick this image up.
- **The ≥3-cell value test is not done and cannot be done from this PR**
— confirming red cells flip requires the prod restart plus a fleet
sweep. Note the ~20 `conversation-error` and ~16 `goto-error` cells are
almost certainly unrelated real bugs this will **not** fix; only the
`abort`/`feature-timeout`/`driver-error` population is in scope.
- **Alerting / scheduled recycle is deliberately out of scope** (one
concern per change). Still worth doing: the documented
`pool-unrecoverable` alarm demonstrably never fired at 1000/1000, and
`cgroupPidsCurrent/cgroupPidsMax > 0.75` would have given ~36h of
warning before the flip.
- Leak rate on the **graceful** `browser.close()` path was not measured
— irrelevant to the fix (tini reaps either way), but it means prod's
exact 757 can't be attributed to crashes alone.



---

# RE-VERIFICATION 2026-08-12 — rebased onto `origin/main`, red-green
re-run from scratch

The proof above was produced 2026-08-03 against a base that predates
`ced993447f` ("copy patches/ into harness build context"), which touches
THIS
Dockerfile. The branch has been rebased onto current `origin/main` and
the
whole red-green was re-run on freshly built images so the numbers
describe the
actual merge candidate.

**Both images built locally from this repo, same machine, same context,
~3 min apart:**

```
showcase-harness:red-main    sha256:b86686e9a06d51f884d5e59e9d15d667fd298284efe7a15622ff3bf2575a3ffd created=2026-08-12T20:15:50Z  (origin/main Dockerfile, /usr/bin/tini ABSENT, Entrypoint=["docker-entrypoint.sh"])
showcase-harness:green-tini  sha256:d666b823f16bda07bf62d35f1d72ef099d13406a61e2f0cd51c99bf51eb14df4 created=2026-08-12T20:18:54Z  (this branch,          /usr/bin/tini present, Entrypoint=["/usr/bin/tini","--"])
```

Identical driver, identical argv, 40 cycles each, runs 18 seconds apart:

```
docker run --rm --pids-limit 1000 -e REPRO_CYCLES=40 -v <repro>:/repro:ro <image> \
  /bin/bash -c "exec node /repro/zombie-repro.mjs"
```

## RED — `showcase-harness:red-main`, `pid1=node` (2026-08-12T20:19:28Z)

```
baseline zombieCount=0 procCount=1 threadCount=7 cgroupPidsCurrent=7 cgroupPidsMax=1000 selfPid=1 pid1=node
cycle=1 pre-kill zombieCount=0 procCount=7 threadCount=76 cgroupPidsCurrent=76 cgroupPidsMax=1000 selfPid=1 pid1=node
cycle=1 zombieCount=5 procCount=6 threadCount=16 cgroupPidsCurrent=16 cgroupPidsMax=1000 selfPid=1 pid1=node
cycle=2 pre-kill zombieCount=5 procCount=12 threadCount=83 cgroupPidsCurrent=83 cgroupPidsMax=1000 selfPid=1 pid1=node
cycle=2 zombieCount=10 procCount=11 threadCount=21 cgroupPidsCurrent=21 cgroupPidsMax=1000 selfPid=1 pid1=node
cycle=10 pre-kill zombieCount=45 procCount=52 threadCount=120 cgroupPidsCurrent=120 cgroupPidsMax=1000 selfPid=1 pid1=node
cycle=10 zombieCount=50 procCount=51 threadCount=61 cgroupPidsCurrent=61 cgroupPidsMax=1000 selfPid=1 pid1=node
cycle=20 pre-kill zombieCount=95 procCount=102 threadCount=174 cgroupPidsCurrent=174 cgroupPidsMax=1000 selfPid=1 pid1=node
cycle=20 zombieCount=100 procCount=101 threadCount=111 cgroupPidsCurrent=111 cgroupPidsMax=1000 selfPid=1 pid1=node
cycle=30 pre-kill zombieCount=145 procCount=152 threadCount=219 cgroupPidsCurrent=219 cgroupPidsMax=1000 selfPid=1 pid1=node
cycle=30 zombieCount=150 procCount=151 threadCount=161 cgroupPidsCurrent=161 cgroupPidsMax=1000 selfPid=1 pid1=node
cycle=40 pre-kill zombieCount=195 procCount=202 threadCount=271 cgroupPidsCurrent=271 cgroupPidsMax=1000 selfPid=1 pid1=node
cycle=40 zombieCount=200 procCount=201 threadCount=211 cgroupPidsCurrent=211 cgroupPidsMax=1000 selfPid=1 pid1=node
final zombieCount=200 procCount=201 threadCount=211 cgroupPidsCurrent=211 cgroupPidsMax=1000 selfPid=1 pid1=node
SUMMARY cycles=40 zombiesBefore=0 zombiesAfter=200 pidsBefore=7 pidsAfter=211 launchFailure=none
```

All 200 leaked processes are `ppid=1`, state `Z` (tail of the final
`/proc` table):

```
 2610     1 Z   1 headless_shell <defunct>
 2612     1 Z   1 headless_shell <defunct>
 2646     1 Z   1 headless_shell <defunct>
 2661     1 Z   1 headless_shell <defunct>
 2662     1 Z   1 headless_shell <defunct>
 2678     1 Z   1 headless_shell <defunct>
 2680     1 Z   1 headless_shell <defunct>
 2717     1 Z   1 headless_shell <defunct>
```

## GREEN — `showcase-harness:green-tini`, `pid1=tini`
(2026-08-12T20:19:46Z)

```
baseline zombieCount=0 procCount=2 threadCount=8 cgroupPidsCurrent=8 cgroupPidsMax=1000 selfPid=7 pid1=tini
cycle=1 pre-kill zombieCount=0 procCount=8 threadCount=76 cgroupPidsCurrent=76 cgroupPidsMax=1000 selfPid=7 pid1=tini
cycle=1 zombieCount=0 procCount=2 threadCount=12 cgroupPidsCurrent=12 cgroupPidsMax=1000 selfPid=7 pid1=tini
cycle=2 pre-kill zombieCount=0 procCount=8 threadCount=78 cgroupPidsCurrent=78 cgroupPidsMax=1000 selfPid=7 pid1=tini
cycle=2 zombieCount=0 procCount=2 threadCount=12 cgroupPidsCurrent=12 cgroupPidsMax=1000 selfPid=7 pid1=tini
cycle=10 pre-kill zombieCount=0 procCount=8 threadCount=79 cgroupPidsCurrent=79 cgroupPidsMax=1000 selfPid=7 pid1=tini
cycle=10 zombieCount=0 procCount=2 threadCount=12 cgroupPidsCurrent=12 cgroupPidsMax=1000 selfPid=7 pid1=tini
cycle=20 pre-kill zombieCount=0 procCount=8 threadCount=76 cgroupPidsCurrent=76 cgroupPidsMax=1000 selfPid=7 pid1=tini
cycle=20 zombieCount=0 procCount=2 threadCount=12 cgroupPidsCurrent=12 cgroupPidsMax=1000 selfPid=7 pid1=tini
cycle=30 pre-kill zombieCount=0 procCount=8 threadCount=77 cgroupPidsCurrent=77 cgroupPidsMax=1000 selfPid=7 pid1=tini
cycle=30 zombieCount=0 procCount=2 threadCount=12 cgroupPidsCurrent=12 cgroupPidsMax=1000 selfPid=7 pid1=tini
cycle=40 pre-kill zombieCount=0 procCount=8 threadCount=79 cgroupPidsCurrent=79 cgroupPidsMax=1000 selfPid=7 pid1=tini
cycle=40 zombieCount=0 procCount=2 threadCount=12 cgroupPidsCurrent=12 cgroupPidsMax=1000 selfPid=7 pid1=tini
final zombieCount=0 procCount=2 threadCount=12 cgroupPidsCurrent=12 cgroupPidsMax=1000 selfPid=7 pid1=tini
SUMMARY cycles=40 zombiesBefore=0 zombiesAfter=0 pidsBefore=8 pidsAfter=12 launchFailure=none
```

`grep -c defunct` over the GREEN run: **0**. `procCount` returns to
**2**
(tini + node) after every cycle — the browser's 6 processes appear
pre-kill
(`procCount=8`, `threadCount` 76–79) and are fully gone post-kill.

|  | RED (`pid1=node`) | GREEN (`pid1=tini`) |
| --- | --- | --- |
| image id | `b86686e9a06d` | `d666b823f16b` |
| cycles | 40 | 40 |
| zombies after | **200** | **0** |
| zombies per crashed browser | **+5** | **0** |
| `pids.current` before → after | 7 → **211** | 8 → **12** |
| `<defunct>` rows in final table | **200** | **0** |
| `launchFailure` | none | none |

## Signals / non-zero exit, both images, this run

```
[showcase-harness:RED   MODE=term-graceful] exitCode=0
    CHILD mode=term-graceful pid=1 ppid=0
    CHILD received SIGTERM at pid=1 — draining
[showcase-harness:RED   MODE=exit-42]   exitCode=42
[showcase-harness:RED   MODE=abort]     exitCode=133
    RED  /proc/1/comm = bash

[showcase-harness:GREEN MODE=term-graceful] exitCode=0
    CHILD mode=term-graceful pid=7 ppid=1
    CHILD received SIGTERM at pid=7 — draining     <- tini FORWARDED it to node
[showcase-harness:GREEN MODE=exit-42]   exitCode=42
[showcase-harness:GREEN MODE=abort]     exitCode=134
    GREEN /proc/1/comm = tini, child self=7
```

SIGTERM reaches node (handler fires at `pid=7`), non-zero exits survive
(42 → 42; abort → 134 = 128+6), so Railway's restart-on-crash is intact.

## The prod leak, measured live the same day

`resource_snapshots` in prod PocketBase, immediately before the
mitigation
restart on the unfixed digest `sha256:80a0c5c2…`:

```
2026-08-12 20:10:00.674Z worker-7abf6 heartbeat pids=1000/1000 zombies=758 procs=778 threads=1000
2026-08-12 20:09:59.783Z worker-5a213 heartbeat pids=1000/1000 zombies=761 procs=781 threads=1000
2026-08-12 20:09:54.868Z worker-de14c heartbeat pids=837/1000  zombies=744 procs=753 threads=837
```

and immediately after it (`init` rows): `pids=164–169/1000 zombies=0
procs=16`.
A new zombie was already recorded at `2026-08-12 20:12:27.182Z
worker-de14c … zombies=1`.

## Cross-arch

Local images are arm64 (`/usr/bin/tini` 68592 bytes); prod builds amd64.
Measured on amd64 directly: `Package: tini / Architecture: amd64 /
Version: 0.19.0-1+b3`, `/usr/bin/tini` 27792 bytes, `tini version
0.19.0`;
package download 267,204 bytes, 749 kB on disk.

## Deploy note

`computePromoteClosure(["showcase-harness"])` = `pocketbase(0),
harness(1),
dashboard(1), harness-workers(1)` — the workers are in the promote
scope.
Prod `startCommand` is `null` and no repo consumer overrides the
entrypoint,
so Railway uses the image's ENTRYPOINT+CMD. **PR #5750 is CLOSED
unmerged**, so
promoting `harness-workers` resets
`multiRegionConfig.us-west2.numReplicas` to
1 and it must be re-asserted to 6 and read back after the promote.


---

# CHANGE 2 — nothing alarmed (worker PID-saturation alarm)

Commit `7f28e9bd39`.

## The gap

The measured prod condition on 2026-08-12 20:09–20:10Z was
`pids=1000/1000`,
`1000/1000`, `837/1000` across three workers, 320 `timeout after
600000ms`
abort rows, an `e2e-smoke` run 42 minutes into a 15-minute cadence with
3 jobs
still pending, prod d6 534/784 vs staging 744/788. **No alarm fired**,
and this
was the second occurrence (2026-08-03, 2026-08-10).

The documented `pool-unrecoverable` alarm did not fire *by
construction*: it is
raised only when `BrowserPool`'s self-heal circuit-breaker exhausts
`selfHealMaxHardRecoveries`. A worker that is PID-starved but still
heartbeating
never reaches that state — it launches browsers fine, it just cannot
fork the
process tree a probe needs.

The signal was already on the wire and read by nobody:

- `worker/registration.ts:192` writes `capacity_pids_current` /
`capacity_pids_max` onto the worker's `workers` row on its ~75s
heartbeat
  (`DEFAULT_WORKER_HEARTBEAT_MS = 75_000`).
- `control-plane/fleet-health.ts` lists that entire roster every 15s
(`DEFAULT_FLEET_HEALTH_INTERVAL_MS`) — and its own comment on the row
type
  said *"the capacity gauges are ignored here."*
- Nothing in non-test source compared `pidsCurrent` to `pidsMax`.

## Where the alarm goes, and why

**Control-plane, not worker.** `writers/status-writer.ts` documents
`fleet-cp`
as *"the only authoritative fleet writer; workers never write status
directly"*,
so a worker cannot raise a `system:` health key. `fleet-health` already
holds
the roster read this needs, on a 15s cadence, so the alarm costs zero
extra PB
traffic.

**Routed to `#oss-alerts`, not to the browser-pool webhook.**
`SLACK_WEBHOOK_BROWSER_POOL_UNRECOVERABLE` appears **nowhere in this
repo
outside its own definition** — `grep` finds it only in `orchestrator.ts`
— so it
is unset everywhere and that alarm has no receiver even when it does
fire.
`SLACK_WEBHOOK_OSS_ALERTS` is a real wired secret that the
family-silence
monitor and the D0-gone monitor already post through. Routing a new
alarm to a
known-unwired webhook would reproduce the exact gap this closes.

## Thresholds

- **Alarm at `pids.current / pids.max >= 0.75`.** At the observed leak
rate
(~1000 PIDs over ~7 days) that is roughly 36 hours of lead time — more
than a
  working day. A busy worker's context budget is nowhere near 750 PIDs.
- **Latched per worker, clearing at 0.65.** The monitor ticks every 15s;
an
unlatched alarm would page ~8600 times across that 36-hour window. An
alarm
that fires constantly is worse than none, so `createFleetHealthMonitor`
now
  **fails loud at construction** on a ratio pair with no hysteresis gap.
- **Evaluated before the online/stale branch**, because the failing
worker is
  fully `online` — it heartbeats on time throughout.
- **Unmeasured gauges never alarm.** `registration.ts` maps the pool's
`-1`
sentinel to `null`; `pidUsageRatio` returns `null` for
null/absent/negative
  current or non-positive max, and null is never read as zero.

---

## RED → GREEN (change 2)

Driver exercises the **real chain end-to-end**, faking only the OS
cgroup read
(`BrowserPoolOptions.cgroupPidsReader`, an existing injectable seam) and
the PB
transport. The column names are whatever the real registration writer
emits and
whatever the real fleet-health reader consumes, so a column drift fails
this
driver:

```
BrowserPool.budget()            [real, probes/helpers/browser-pool.ts]
  -> workerCapacityFromBudget   [real, fleet/contracts.ts]
  -> registerWorker()           [real, fleet/worker/registration.ts]
  -> workers row
  -> createFleetHealthMonitor().checkOnce()
                                [real, fleet/control-plane/fleet-health.ts]
  -> alarm sink
```

Identical command both sides; only the source differs:

```
./node_modules/.bin/tsx <scratch>/drive-alarm.mts
```

### RED — unmodified source

```
=== A1 SATURATED 900/1000 (ratio 0.90) ===
  pool.budget() pids      : 900/1000
  workers row gauges      : capacity_pids_current=900 capacity_pids_max=1000
  fleet-health cycles run : 1
  ALARM HOOK CALLS        : 0
  result.pidSaturated     : <field does not exist>
  error-level log events  : <none>

=== A2 CEILING   1000/1000 (ratio 1.00) ===
  pool.budget() pids      : 1000/1000
  workers row gauges      : capacity_pids_current=1000 capacity_pids_max=1000
  fleet-health cycles run : 1
  ALARM HOOK CALLS        : 0
  result.pidSaturated     : <field does not exist>
  error-level log events  : <none>

=== A6 LATCH     900/1000 over 5 cycles ===
  fleet-health cycles run : 5
  ALARM HOOK CALLS        : 0
  result.pidSaturated     : <field does not exist>
  error-level log events  : <none>
```

The exact prod condition — a worker at the ceiling — produces **zero**
alarms.

### GREEN — with this change

```
=== A1 SATURATED 900/1000 (ratio 0.90) ===
  pool.budget() pids      : 900/1000
  workers row gauges      : capacity_pids_current=900 capacity_pids_max=1000
  fleet-health cycles run : 1
  ALARM HOOK CALLS        : 1
  result.pidSaturated     : 1
  error-level log events  : ["fleet.health.worker-pid-saturated"]
  ALARM PAYLOAD           : {"workerId":"worker-drv","pidsCurrent":900,"pidsMax":1000,"ratio":0.9,"threshold":0.75,"lastHeartbeatAt":"2026-08-12T20:44:54.244Z","observedAt":"2026-08-12T20:44:54.244Z"}

=== A2 CEILING   1000/1000 (ratio 1.00) ===
  ALARM HOOK CALLS        : 1
  result.pidSaturated     : 1
  error-level log events  : ["fleet.health.worker-pid-saturated"]
  ALARM PAYLOAD           : {"workerId":"worker-drv","pidsCurrent":1000,"pidsMax":1000,"ratio":1,"threshold":0.75,"lastHeartbeatAt":"2026-08-12T20:44:54.253Z","observedAt":"2026-08-12T20:44:54.253Z"}
```

### The alarm must also stay QUIET — same run, same command

```
=== A3 QUIET     500/1000 (ratio 0.50) ===
  ALARM HOOK CALLS        : 0
  result.pidSaturated     : 0
  error-level log events  : <none>

=== A4 QUIET     740/1000 (ratio 0.74, just under) ===
  ALARM HOOK CALLS        : 0
  result.pidSaturated     : 0
  error-level log events  : <none>

=== A5 QUIET     -1/-1 (cgroup unreadable) ===
  pool.budget() pids      : -1/-1
  workers row gauges      : capacity_pids_current=null capacity_pids_max=null
  ALARM HOOK CALLS        : 0
  result.pidSaturated     : 0
  error-level log events  : <none>

=== A6 LATCH     900/1000 over 5 cycles ===
  fleet-health cycles run : 5
  ALARM HOOK CALLS        : 1        <- once, not five times
```

`A4` pins the boundary at 0.74. `A5` pins the off-Linux case: the `-1`
sentinel
lands as `null` on the row and stays silent rather than reading as `0`.
`A6`
pins the latch — 5 saturated cycles, 1 alarm.

---

# CHANGE 3 — saturated workers kept claiming (PID headroom claim gate)

Commit `63ef4081c2`.

## The defect

`fleet/worker/worker-loop.ts` had exactly one conditional in the claim
loop:

```ts
if (budget.available <= 0) { … idle … }
```

and `available` is free Playwright **browser-context** slots and nothing
else —
`browser-pool.ts`: `available: Math.max(0, this.maxContexts -
this.liveContextCount)`.
Context slots have no relationship to cgroup PIDs. A worker whose
container has
leaked to `pids=1000/1000` therefore still advertises **full** capacity,
keeps
winning claims, cannot fork the browser tree, and burns each job's
entire
600000ms lease before aborting. That is the mechanism behind the 320
abort rows.

## Blast radius — what happens when ALL workers are saturated

The gate deliberately reuses the **same decline-and-idle path** as the
existing
no-budget branch, which is what makes total saturation safe:

- the job is **never claimed**, so it is never dropped and never
requeued — it
stays `pending` for a healthy worker, or for this one after a redeploy;
- the loop then sleeps a full `pollIntervalMs`, so a fully-saturated
fleet
  **idles at the poll cadence** instead of spinning;
- the queue **stalls visibly**: `probe_jobs` rows pile up pending, a
rising-edge
`fleet.worker.pid-headroom-exhausted` warn says why (warn → stderr →
Sentry;
  steady state drops to debug so a multi-hour stall does not flood), and
change 2's `system:worker-pid-saturation` alarm fired at 0.75 **before**
this
  gate engaged at 0.90.

A stalled, alarmed queue is recoverable by redeploy. Claim-fail-repeat
silently
burned the whole cadence.

## Why the gate is 0.90 and the alarm is 0.75

They do different jobs and must not be equal. 0.75 pages an operator
while the
worker is still perfectly able to run jobs; gating dispatch that early
would
convert a warning into ~36 hours of withheld fleet capacity. 0.90 is
where we
stop trusting the worker to fork at all — 100 free PIDs at the prod
ceiling.
**That reserve is chosen, not derived: the per-job PID cost of a
chromium
context tree is not measured**, hence the `WORKER_PID_CLAIM_GATE_RATIO`
override. The invariant that matters is ordering — the alarm always
fires before
capacity is withdrawn.

The gate is **inert** when the cgroup gauges are unreadable
(`pidUsageRatio` →
`null`: off-Linux, every macOS dev box), so local workers claim exactly
as
before.

---

## RED → GREEN (change 3)

Driver runs the **real `startWorkerLoop`** against the **real
`BrowserPool`**
budget path, faking only the cgroup read and the queue transport. The
queue fake
holds a real `pending` list, so *"was the job dropped / does it stay
pending"* is
directly observed, not inferred. `budget()` calls are counted as a
loop-iteration proxy for the spin check.

Identical command both sides:

```
./node_modules/.bin/tsx <scratch>/drive-gate.mts
```

### RED — unmodified source

```
=== B1 SATURATED  1 worker @ 1000/1000, 3 jobs pending ===
  workers=1  cgroup pids=1000/1000  contexts available=24
  window                  : 600ms @ poll 50ms
  queue.claimNext CALLS   : 15
  jobs CLAIMED            : 3 ["job-1","job-2","job-3"]
  jobs STILL PENDING      : 0 []
  jobs REPORTED           : 3
  loop iterations         : 15

=== B2 ALL-SATURATED  3 workers @ 1000/1000, 3 jobs pending ===
  workers=3  cgroup pids=1000/1000  contexts available=24
  queue.claimNext CALLS   : 39
  jobs CLAIMED            : 3 ["job-1","job-2","job-3"]
  jobs STILL PENDING      : 0 []
  jobs REPORTED           : 3
  loop iterations         : 39
```

A worker at the PID ceiling claims **all three jobs**. In prod each of
those
becomes a 600000ms abort.

### GREEN — with this change

```
=== B1 SATURATED  1 worker @ 1000/1000, 3 jobs pending ===
  workers=1  cgroup pids=1000/1000  contexts available=24
  window                  : 600ms @ poll 50ms
  queue.claimNext CALLS   : 0
  jobs CLAIMED            : 0 []
  jobs STILL PENDING      : 3 ["job-1","job-2","job-3"]
  jobs REPORTED           : 0
  loop iterations         : 12 (spin check: bounded by window/poll)
```

`claimNext` is never called; all three jobs are **still pending** — not
dropped,
not requeued.

### ALL workers saturated — the blast-radius case

```
=== B2 ALL-SATURATED  3 workers @ 1000/1000, 3 jobs pending ===
  workers=3  cgroup pids=1000/1000  contexts available=24
  window                  : 600ms @ poll 50ms
  queue.claimNext CALLS   : 0
  jobs CLAIMED            : 0 []
  jobs STILL PENDING      : 3 ["job-1","job-2","job-3"]
  jobs REPORTED           : 0
  loop iterations         : 36 (spin check: bounded by window/poll)
```

Zero claims, **3 of 3 jobs still pending**, and 36 iterations across 3
workers
over a 600ms window at a 50ms poll — i.e. 12 per worker, the poll
cadence. No
spin, no loss.

### The gate must NOT engage below threshold — same run, same command

```
=== B3 HEALTHY  1 worker @ 100/1000, 3 jobs pending ===
  queue.claimNext CALLS   : 15
  jobs CLAIMED            : 3   jobs STILL PENDING : 0   jobs REPORTED : 3

=== B4 UNDER-GATE  1 worker @ 890/1000, 3 jobs pending ===
  queue.claimNext CALLS   : 15
  jobs CLAIMED            : 3   jobs STILL PENDING : 0   jobs REPORTED : 3

=== B5 UNMEASURED  1 worker @ -1/-1, 3 jobs pending ===
  queue.claimNext CALLS   : 15
  jobs CLAIMED            : 3   jobs STILL PENDING : 0   jobs REPORTED : 3
```

`B4` is the load-bearing one: 0.89 is **above** change 2's 0.75 alarm
and below
this gate. The operator has been paged and the worker keeps working —
which is
the whole reason the two thresholds differ. `B5` pins the off-Linux
case.

---

# Tests and gates (changes 2 and 3)

`showcase/harness`, on the pushed head `63ef4081c2`:

| Gate | Command | Result |
|---|---|---|
| Typecheck | `npx tsc --noEmit -p tsconfig.json` | exit 0 |
| Lint | `npx oxlint src/fleet src/orchestrator.ts` | 0 errors; warning
count unchanged vs base (2 on `fleet-health.ts` before and after) |
| Format | `npx oxfmt --write` | clean |
| Unit suite | `vitest run` | **3696 passed, 18 skipped, 1 failed** —
175/178 files pass |

The single failure is `src/probes/frontend-matrix.test.ts` —
**pre-existing**.
Verified by stashing this branch's changes and re-running it on the
unmodified
tree, where it fails identically (`1 failed | 5 passed`).

14 tests are new (`3682 → 3696`).

**Mutation-tested for vacuity.** With the four source files reverted to
`e66fb1af13` and the new test files kept, **11 of the new tests fail**:

```
Test Files  2 failed (2)
     Tests  11 failed | 80 passed (91)

FAIL fleet-health.test.ts > PID saturation > alarms on an ONLINE worker whose PID gauges cross the threshold
FAIL fleet-health.test.ts > PID saturation > stays silent below the threshold, including just under it
FAIL fleet-health.test.ts > PID saturation > stays silent when the gauges are UNMEASURED (null / unbounded max)
FAIL fleet-health.test.ts > PID saturation > is EDGE-triggered: a sustained saturation alarms once, not every cycle
FAIL fleet-health.test.ts > PID saturation > re-arms only after the worker drops below the CLEAR ratio
FAIL fleet-health.test.ts > PID saturation > never lets a throwing alarm hook abort the cycle
FAIL fleet-health.test.ts > PID saturation > fails loud on a ratio config that would alarm every cycle
FAIL worker-loop.test.ts  > PID headroom gate > declines to claim at the PID ceiling — the job is never claimed, so it stays pending
FAIL worker-loop.test.ts  > PID headroom gate > declines at the gate ratio boundary (0.90)
FAIL worker-loop.test.ts  > PID headroom gate > honours an injected gate ratio
FAIL fleet-health.test.ts > checkOnce > never throws when the roster read fails — returns an empty cycle
```

The three that pass on both sides are the sub-threshold controls (`still
claims
just BELOW the gate`, `claims normally on a healthy worker`, `stays
INERT when
the cgroup gauges are unreadable`) — they are supposed to be unchanged
by the
fix, and they are.

# New env knobs (all optional, all defaulted)

| Var | Default | Effect |
|---|---|---|
| `WORKER_PID_SATURATION_RATIO` | `0.75` | Control-plane alarm
threshold. |
| `WORKER_PID_SATURATION_CLEAR_RATIO` | `0.65` | Alarm latch hysteresis
clear. |
| `WORKER_PID_CLAIM_GATE_RATIO` | `0.90` | Worker claim-gate threshold.
|

An out-of-range override on the two alarm ratios falls back to the
default
rather than tripping the fail-loud guard and taking the control-plane
down over
a typo'd env var.

# Not verified

- Neither change 2 nor change 3 has been exercised against **live prod
or
staging PocketBase**; both red-greens are local, on the real modules
with the
  cgroup read and PB/queue transport injected.
- **No Slack post was sent.** `SLACK_WEBHOOK_OSS_ALERTS` was not set in
the
driver, so the send leg was not exercised end-to-end — only that its
failure
  is swallowed without costing the durable status row.
- The per-job PID cost of a chromium context tree is **not measured**,
so the
  0.90 gate's 100-PID reserve is a chosen value.
zeekay pushed a commit to Dream-AI-4444/CopilotKit that referenced this pull request Sep 11, 2026
…te integration slug; sort-ordered preview selection

- Extract findFrameworksWithCell into @/lib/docs-render so the docs
  catch-all and framework-scoped catch-all share one implementation
  instead of carrying a near-identical local copy in each (finding CopilotKit#3).
- Validate /docs/integrations/<slug> against the registry with
  notFound() when the slug is unknown. Previously a crafted URL like
  /docs/integrations/fake-framework silently fell through to an empty
  nav tree, indistinguishable from a valid integration with no scoped
  content (finding CopilotKit#4).
- Sort integrations by sort_order then slug before picking the
  animated preview URL. Registry iteration order alone isn't
  deterministic w.r.t. the visual priority the docs UI shows
  everywhere else, so the preview now matches (finding CopilotKit#5).
zeekay pushed a commit to Dream-AI-4444/CopilotKit that referenced this pull request Sep 11, 2026
…null-alt filter, registry-gated landing cards

- Reject RESERVED_ROUTE_SLUGS at the handler as defense-in-depth.
  Next.js already prefers exact-match top-level routes over this
  catch-all, so /docs, /ag-ui, etc. never reach here under normal
  routing — but if the registry ever ships an integration whose slug
  collides with a reserved segment, the handler now short-circuits
  with notFound() rather than rendering garbage (finding CopilotKit#6).
- Import the shared findFrameworksWithCell helper instead of a
  duplicated local copy (finding CopilotKit#3 follow-through).
- Filter out unresolved alternative-framework slugs BEFORE mapping
  to React fragments so the ", " separator aligns with the final
  rendered count. The pre-filter index previously emitted stray
  commas when an entry dropped to null mid-sequence (finding CopilotKit#7).
- FrameworkLandingPage's four hardcoded LandingCards are now gated by
  registry integration.features presence: strands (no HITL support)
  no longer shows a dead "Human-in-the-Loop" card. The card
  definitions are hoisted into a module-level constant with a TODO
  pointing at the eventual feature-id → doc-slug mapping
  (finding CopilotKit#8).
- Declare export const dynamicParams = true explicitly so a future
  migration to output: "export" fails loudly here (under static
  export dynamicParams must be false) rather than silently 404ing
  every /<framework>/<slug> URL (finding CopilotKit#9).
zeekay pushed a commit to Dream-AI-4444/CopilotKit that referenced this pull request Sep 11, 2026
## CI hygiene fixes

Four direct-fix items surfaced during the 2026-04-16 QA/E2E blitz,
bundled as one PR with one commit per fix:

1. **`test_unit.yml` paths-ignore** — add `showcase/**` +
`sdk-python/**` (prevents spurious TS unit matrix runs on showcase-only
or sdk-python-only PRs). `sdk-python-old/**` was mentioned in the plan
but doesn't exist on main; only the two existing dirs are added.
2. **`test_doc-examples.yml`** — scope PR trigger to `branches: [main]`
(matches convention of other workflows).
3. **`e2e_dojo.yml`** — symmetric `.changeset` path filter on push+PR
(was asymmetric — already in the `dorny/paths-filter` step's `ts:` list,
so this aligns the trigger).
4. **`starter-smoke.yml`** — rename internal job id (`starter-smoke` →
`smoke-starter`) and artifact name pattern (cosmetic; matches the new
`test_<layer>-<target>` / `smoke-<layer>` naming convention; no external
consumers).

### Fix skipped

**`showcase_smoke-monitor.yml` slug normalization** (item CopilotKit#10 in the
Notion page) — inspecting the file, it already uses the
`showcase/packages/` slug convention (`ms-agent-python`,
`ms-agent-dotnet`, `strands`). The apparent inconsistency is actually in
`starter-smoke.yml`, whose matrix keys must stay as
`ms-agent-framework-*` / `strands-python` because they are literal
directory names in `examples/integrations/` (used as `working-directory:
examples/integrations/${{ matrix.starter }}`). So there is no actionable
change here — the two files use different slug conventions *by
necessity*, because they target different directories (deployed
`showcase/packages/*` vs. local `examples/integrations/*`). Flagging for
the author of the blitz notes in case the actual concern was something
else.

Refs: [Bugs Found During
Blitz](https://www.notion.so/3443aa381852812fb595c5118dd68818) items CopilotKit#3,
CopilotKit#8, CopilotKit#9, CopilotKit#12.
jpr5 added a commit that referenced this pull request Sep 17, 2026
…#7256)

## TL;DR

Keep filtered probe runs from changing excluded dashboard cells, and
persist selected D5 results with durable, atomic retry receipts. This PR
combines the reviewed reporting foundations from #7222 with the
dependent D5 persistence repair. It supersedes #7222; that parent is
deliberately not merged separately.

PocketBase prerequisite #7255 is already merged and verified on staging:
normal `:latest`, sole successful deployment, exact hook/migration
bytes, live 2 MiB receipt field and authenticated endpoint. This PR
contains only 13 harness files in two concern commits.

## Actual local RED → GREEN on the final composition

The fresh official main-baseline image and the final candidate both
execute the actual native browser probes successfully for Microsoft
.NET, .NET Harness, and Mastra. On main, each selected run incorrectly
also changes the excluded full-framework aggregate
(`unchangedControls:false`, two reds cleared). The candidate preserves
excluded records and clears only the selected row.

The reviewed #7222 intermediate image exposes an additional D5 namespace
regression: the same successful native observations leave the selected
row red and summary total zero. The combined candidate turns the SAME
three row IDs green, records total one, preserves excluded records, and
replays without changing status/history. Thus main's selected row was
already green; this PR does not mislabel it as an application failure or
claim three new application fixes.

Private PocketBase rows are explicitly labeled test sentinels for
detecting persistence loss and out-of-scope writes; they are not
invented application failures. The real native verdicts pass in every
phase.

All RED phases were run locally before restoring the respective reviewed
source files. Candidate source
`4b1c76bdfb9f9d9d6bf06e381ad7615ba57217b2` exactly matches the
independently reviewed bytes; the official local image is
`sha256:e97ece5636d37de7743ae95d19d66ec8e2ae21b7e27f7cb2fd21fb510b8c8615`.
Native browser/worker/real PocketBase runs used isolated local services
and AIMock, not CI or fabricated unit results.

### S05 raw final observer output

`red-main` — observer exit 2:

```json
{"actualWorkerPassed":true,"persistedState":"green","rollup":{"total":1,"passed":1,"failed":0},"agg":{"runRowId":"8hhqhmmfztnabna","statusOutcomes":[{"previousState":"red","newState":"green","transition":"red_to_green","firstFailureAt":null,"failCount":0,"persisted":true},{"previousState":"red","newState":"green","transition":"red_to_green","firstFailureAt":null,"failCount":0,"persisted":true}],"overlayOutcomes":[],"skipped":false,"outageSkippedKeys":[],"droppedCommError":false,"corruptStateSkippedKeys":[]}}
```
`red-parent` — observer exit 1:

```json
{"actualWorkerPassed":true,"persistedState":"red","rollup":{"total":1,"passed":1,"failed":0},"agg":{"runRowId":"gftdymmzxgvq2qm","statusOutcomes":[],"overlayOutcomes":[],"skipped":false,"outageSkippedKeys":[],"droppedCommError":false,"corruptStateSkippedKeys":[]}}
```
`green-candidate` — observer exit 0:

```json
{"actualWorkerPassed":true,"persistedState":"green","rollup":{"total":1,"passed":1,"failed":0},"agg":{"runRowId":"8ck5a5rs8floyzb","statusOutcomes":[{"previousState":"red","newState":"green","transition":"red_to_green","firstFailureAt":null,"failCount":0,"persisted":true}],"overlayOutcomes":[],"skipped":false,"outageSkippedKeys":[],"droppedCommError":false,"corruptStateSkippedKeys":[]}}
```

### S06 raw final observer output

`red-main` — observer exit 2:

```json
{"actualWorkerPassed":true,"persistedState":"green","rollup":{"total":1,"passed":1,"failed":0},"agg":{"runRowId":"wyftkyd5fy9344w","statusOutcomes":[{"previousState":"red","newState":"green","transition":"red_to_green","firstFailureAt":null,"failCount":0,"persisted":true},{"previousState":"red","newState":"green","transition":"red_to_green","firstFailureAt":null,"failCount":0,"persisted":true}],"overlayOutcomes":[],"skipped":false,"outageSkippedKeys":[],"droppedCommError":false,"corruptStateSkippedKeys":[]}}
```
`red-parent` — observer exit 1:

```json
{"actualWorkerPassed":true,"persistedState":"red","rollup":{"total":1,"passed":1,"failed":0},"agg":{"runRowId":"bjgumkld7fcs91z","statusOutcomes":[],"overlayOutcomes":[],"skipped":false,"outageSkippedKeys":[],"droppedCommError":false,"corruptStateSkippedKeys":[]}}
```
`green-candidate` — observer exit 0:

```json
{"actualWorkerPassed":true,"persistedState":"green","rollup":{"total":1,"passed":1,"failed":0},"agg":{"runRowId":"3vc19es94r8e3ph","statusOutcomes":[{"previousState":"red","newState":"green","transition":"red_to_green","firstFailureAt":null,"failCount":0,"persisted":true}],"overlayOutcomes":[],"skipped":false,"outageSkippedKeys":[],"droppedCommError":false,"corruptStateSkippedKeys":[]}}
```

### S07 raw final observer output

`red-main` — observer exit 2:

```json
{"actualWorkerPassed":true,"persistedState":"green","rollup":{"total":1,"passed":1,"failed":0},"agg":{"runRowId":"30wkjgnotspcl1e","statusOutcomes":[{"previousState":"red","newState":"green","transition":"red_to_green","firstFailureAt":null,"failCount":0,"persisted":true},{"previousState":"red","newState":"green","transition":"red_to_green","firstFailureAt":null,"failCount":0,"persisted":true}],"overlayOutcomes":[],"skipped":false,"outageSkippedKeys":[],"droppedCommError":false,"corruptStateSkippedKeys":[]}}
```
`red-parent` — observer exit 1:

```json
{"actualWorkerPassed":true,"persistedState":"red","rollup":{"total":1,"passed":1,"failed":0},"agg":{"runRowId":"j74kmxgcwz1qyuv","statusOutcomes":[],"overlayOutcomes":[],"skipped":false,"outageSkippedKeys":[],"droppedCommError":false,"corruptStateSkippedKeys":[]}}
```
`green-candidate` — observer exit 0:

```json
{"actualWorkerPassed":true,"persistedState":"green","rollup":{"total":1,"passed":1,"failed":0},"agg":{"runRowId":"xdrsr5ctvrgdybd","statusOutcomes":[{"previousState":"red","newState":"green","transition":"red_to_green","firstFailureAt":null,"failCount":0,"persisted":true}],"overlayOutcomes":[],"skipped":false,"outageSkippedKeys":[],"droppedCommError":false,"corruptStateSkippedKeys":[]}}
```

## Review and validation

Independent composition review confirms all 13 file hashes, the six
parent-only files' 26-report review coverage, and the D5 changes'
12-report final review. Both reviews have zero remaining mandatory
findings. Current official local Docker build and three native paired
checks pass. Host formatter, lint (102 reviewed warnings, zero errors),
explicit typecheck, full suite (3,841 passed; 18 existing skips), and
full production build all pass. CI must pass before merge.

The prior real PocketBase/consumer failure proofs remain bound to
identical reviewed behavior, with all 88 frozen artifact hashes
reverified. These cover partial writes, lost responses, prefix retries,
process restart/stale sweep, observation identity, missing selected
observations, structural driver errors, summary accounting, malformed
timestamps, and concurrent row creation.


<details><summary>Preserved actual local A1 failure-surface
proof</summary>

# A1 raw local red-green proof for PR body

Selected status writes previously resolved after a PocketBase write
failure, so the result consumer latched the job and the run became
terminal without the required observation. Atomic per-job receipts now
preserve retryability and suppress replayed writes, including after
stale-run sweep and process restart.

TS commit `4994eb27f033eab4b24b960298e2fa271b405e0d`; PB component
`7e6b695cd67fe1f0939612337bd8eb2caff70367`. Private PocketBase on 42910,
real result consumer and real status writer. Native S06 capture
replayed; additional selected prefix, negative state, and
communication-error inputs are explicitly synthetic accepted protocol
cases. They are not native-producer bug claims.

## Single required status write failure

Red (`red.log`), then green (`atomic-single-green.log`):

```text
{"first":{"processed":1,"failures":0},"retry":{"processed":0,"failures":0},"replay":{"processed":0,"failures":0},"checks":{"failureNotAcknowledged":false,"noFalseTerminal":false,"retrySucceeded":false,"sameRun":true,"noReplayWrites":true,"oneHistoryAdded":false}}
{"first":{"processed":0,"failures":1},"retry":{"processed":1,"failures":0},"replay":{"processed":0,"failures":0},"checks":{"failureNotAcknowledged":true,"noFalseTerminal":true,"retrySucceeded":true,"sameRun":true,"noReplayWrites":true,"oneHistoryAdded":true}}
```

## Multiple selected cells: successful prefix then later failure

Red (`multi-candidate.log`), then green (`atomic-multi-final.log`):

```text
{"first":{"processed":0,"failures":1},"retry":{"processed":1,"failures":0},"replay":{"processed":0,"failures":0},"checks":{"failureNotAcknowledged":true,"noFalseTerminal":true,"retrySucceeded":true,"sameRun":true,"prefixHistoryDuplicated":true,"noReplayWrites":true,"oneHistoryAdded":false}}
{"first":{"processed":0,"failures":1},"retry":{"processed":1,"failures":0},"replay":{"processed":0,"failures":0},"checks":{"failureNotAcknowledged":true,"noFalseTerminal":true,"retrySucceeded":true,"sameRun":true,"prefixHistoryPreserved":true,"noReplayWrites":true,"oneHistoryAdded":true}}
```

## Real stale sweep and child-process restart

Red (`restart-red.log`), then green (`restart-final.log`):

```text
{"first":{"processed":0,"failures":1},"retry":{"processed":1,"failures":0},"replay":{"processed":0,"failures":0},"checks":{"actualSweep":true,"newProcess":true,"prefixStatePreserved":true,"failureNotAcknowledged":true,"noFalseTerminal":true,"retrySucceeded":false,"sameRun":true,"prefixHistoryPreserved":true,"noReplayWrites":true,"oneHistoryAdded":false}}
{"first":{"processed":0,"failures":1},"retry":{"processed":1,"failures":0},"replay":{"processed":0,"failures":0},"checks":{"actualSweep":true,"newProcess":true,"prefixStatePreserved":true,"failureNotAcknowledged":true,"noFalseTerminal":true,"retrySucceeded":true,"sameRun":true,"prefixHistoryPreserved":true,"noReplayWrites":true,"oneHistoryAdded":true}}
```

## New job identity and overlay fallback route change

Red (`identity-route-red.log`), then green (`identity-route-final.log`):

```text
{"distinctJobCounted":true,"distinctJobHistory":true,"oldReplayPreserved":true,"fallbackPersisted":true,"routeRetrySucceeded":true,"fallbackReplayPreserved":false}
{"distinctJobCounted":true,"distinctJobHistory":true,"oldReplayPreserved":true,"fallbackPersisted":true,"routeRetrySucceeded":true,"fallbackReplayPreserved":true}
```

## Selected history failure must roll back status and retry

Red (`history-red.log`), then green (`history-green.log`):

```text
{"first":{"processed":1,"failures":0},"retry":{"processed":0,"failures":0},"replay":{"processed":0,"failures":0},"checks":{"statusRolledBack":false,"failureNotAcknowledged":false,"noFalseTerminal":false,"retrySucceeded":false,"sameRun":true,"noReplayWrites":true,"oneHistoryAdded":false}}
{"first":{"processed":0,"failures":1},"retry":{"processed":1,"failures":0},"replay":{"processed":0,"failures":0},"checks":{"statusRolledBack":true,"failureNotAcknowledged":true,"noFalseTerminal":true,"retrySucceeded":true,"sameRun":true,"noReplayWrites":true,"oneHistoryAdded":true}}
```

## Lost response after real transaction commit

The proof consumes and discards one successful HTTP response after
PocketBase commits. The client retries and gets the stored receipt; one
history row lands. This tests the new atomic boundary, not an invented
pre-fix missing-endpoint bug.

```text
{"first":{"processed":1,"failures":0},"retry":{"processed":0,"failures":0},"replay":{"processed":0,"failures":0},"checks":{"committedResponseWasLost":true,"atomicRequestRetried":true,"consumerSucceeded":true,"oneHistoryAdded":true,"noReplayWrites":true,"finalStateGreen":true}}
```

Validation: full harness 3,832 passed / 18 existing skipped;
typecheck/build/format pass; lint 0 errors / 10 pre-existing warnings.
Schema/endpoint absence fails loudly; deploy PB migration and hook
before the new control-plane writer. Raw complete logs and JSON
snapshots are hash-bound in final-receipt.json.

</details>

<details><summary>Preserved actual local A2 failure-surface
proof</summary>

# A2 native driver diagnostic preservation

Scoped native D5 jobs exclude their full aggregate from status writes. A
genuine driver exception returns empty cells, `aggregateState: error`,
and the diagnostic in `aggregateSignal`, with no communication error.
The selected cells therefore received no error history.

The fix projects the driver error onto each selected key through the
existing status-writer error path. It preserves the prior durable
observation, advances its observed timestamp, and stores the actual
diagnostic in error history. It leaves executed-cell counts at zero and
the run failed. It does not modify the full aggregate or excluded cells.

## Local red-green proof

The same untouched native `createE2eFullDriver` runs through real
`runClaimedJob`, real queue report, real `createResultConsumer`, and a
private real PocketBase at port 42920. The accepted malformed `features`
input triggers the actual native TypeError `featureSource.filter is not
a function`. No driver, consumer, queue, or writer stub is used.
Baseline runtime is the existing eb3 proof image; green changes only the
compiled aggregator module using a read-only mount. This demonstrates
persistence of an actual native exception, not a successful test or a
product-cell green flip.

All complete outputs are retained next to this document (`red.log/json`,
`green.log/json`, `proof-receipt.json`). The selected status row remains
red, keeps its ID, and advances observed_at; its error history now
contains the exact diagnostic. The run remains failed with zero executed
cells. Controls and replay are unchanged.

### RED raw output

```text
WARNING: The requested image's platform (linux/amd64) does not match the detected host platform (linux/arm64/v8) and no specific platform was requested
{"level":"warn","msg":"pb-client.legacy-admin-auth-fallback","ts":"2026-09-17T05:33:50.251Z","hint":"/_superusers returned 404 — falling back to /api/admins (PB ≤0.22). Disable this warn after upgrading to PB 0.23+."}
{"level":"error","msg":"fleet.worker.job-driver-error","ts":"2026-09-17T05:33:50.778Z","workerId":"local-d5-worker","jobId":"sxlxy3eoil7cd2l","probeKey":"d5-single-pill-e2e:a2-driver-error","errName":"TypeError","err":"featureSource.filter is not a function"}
{
  "driverFailed": true,
  "diagnosticPreserved": false,
  "consumed": {
    "processed": 1,
    "failures": 0
  },
  "selectedHistory": [],
  "unchangedControls": true,
  "replayPreserved": true,
  "runs": {
    "page": 1,
    "perPage": 100,
    "totalItems": 1,
    "totalPages": 1,
    "items": [
      {
        "collectionId": "mbsz2pvgffrkd7y",
        "collectionName": "probe_runs",
        "created": "2026-09-17 05:33:50.803Z",
        "duration_ms": 4,
        "finished_at": "2026-09-17 05:33:50.804Z",
        "id": "9c6t0kjwihf1643",
        "job_id": "sxlxy3eoil7cd2l",
        "probe_id": "d5-single-pill-e2e:a2-driver-error",
        "started_at": "2026-09-17 05:33:50.800Z",
        "state": "failed",
        "summary": {
          "failed": 0,
          "passed": 0,
          "redsCleared": 0,
          "redsIntroduced": 0,
          "total": 0
        },
        "triggered": false,
        "updated": "2026-09-17 05:33:50.811Z"
      }
    ]
  }
}
```

### GREEN raw output

```text
{"level":"warn","msg":"pb-client.legacy-admin-auth-fallback","ts":"2026-09-17T05:35:29.220Z","hint":"/_superusers returned 404 — falling back to /api/admins (PB ≤0.22). Disable this warn after upgrading to PB 0.23+."}
{"level":"error","msg":"fleet.worker.job-driver-error","ts":"2026-09-17T05:35:29.687Z","workerId":"local-d5-worker","jobId":"ptpk5w3sgljiyjx","probeKey":"d5-single-pill-e2e:a2-driver-error","errName":"TypeError","err":"featureSource.filter is not a function"}
{
  "driverFailed": true,
  "diagnosticPreserved": true,
  "consumed": {
    "processed": 1,
    "failures": 0
  },
  "selectedHistory": [
    {
      "collectionId": "eg1ekz8jfyeploi",
      "collectionName": "status_history",
      "created": "2026-09-17 05:35:29.741Z",
      "dimension": "d5",
      "id": "fjsywn62kx5opk4",
      "key": "d5:a2-driver-error/shared-state",
      "observed_at": "2026-09-17 05:35:29.687Z",
      "signal": {
        "error": "featureSource.filter is not a function"
      },
      "state": "red",
      "transition": "error",
      "updated": "2026-09-17 05:35:29.741Z"
    }
  ],
  "unchangedControls": true,
  "replayPreserved": true,
  "runs": {
    "page": 1,
    "perPage": 100,
    "totalItems": 2,
    "totalPages": 1,
    "items": [
      {
        "collectionId": "mbsz2pvgffrkd7y",
        "collectionName": "probe_runs",
        "created": "2026-09-17 05:33:50.803Z",
        "duration_ms": 4,
        "finished_at": "2026-09-17 05:33:50.804Z",
        "id": "9c6t0kjwihf1643",
        "job_id": "sxlxy3eoil7cd2l",
        "probe_id": "d5-single-pill-e2e:a2-driver-error",
        "started_at": "2026-09-17 05:33:50.800Z",
        "state": "failed",
        "summary": {
          "failed": 0,
          "passed": 0,
          "redsCleared": 0,
          "redsIntroduced": 0,
          "total": 0
        },
        "triggered": false,
        "updated": "2026-09-17 05:33:50.811Z"
      },
      {
        "collectionId": "mbsz2pvgffrkd7y",
        "collectionName": "probe_runs",
        "created": "2026-09-17 05:35:29.728Z",
        "duration_ms": 24,
        "finished_at": "2026-09-17 05:35:29.747Z",
        "id": "7c7otr4omcoknz5",
        "job_id": "ptpk5w3sgljiyjx",
        "probe_id": "d5-single-pill-e2e:a2-driver-error",
        "started_at": "2026-09-17 05:35:29.723Z",
        "state": "failed",
        "summary": {
          "failed": 0,
          "passed": 0,
          "redsCleared": 0,
          "redsIntroduced": 0,
          "total": 0
        },
        "triggered": false,
        "updated": "2026-09-17 05:35:29.752Z"
      }
    ]
  }
}
```

The final PR body must include these raw outputs; this worker does not
create or push a PR.

</details>

<details><summary>Preserved actual local A4 failure-surface
proof</summary>

# A4 proof and handoff

Commit `6f4f00a68859b528661962be70b75bbb358ef777`, base
`eb3d9466e4648cea9ed509b0fa662ef9e9deb0ed`. Clean isolated concern
branch. Only aggregator source and regression tests changed. No
PR/push/deployment.

Scoped totals now use valid original observations retained by the
existing canonical-key write plan. First occurrence remains
authoritative without commError; trusted-negative replacement remains
authoritative with commError. Synthetic fallback rows do not count.
Explicit driver/communication errors remain failed, and rejecting all
original selected observations cannot manufacture a successful run.

## Integration

`observationProjectionCount` is recorded before fallback insertion.
Preserve that boundary when applying A2/A3 so synthetic diagnostics
remain excluded from totals. A1 changes only the subsequent writer
failure catch and does not conflict semantically. No new public helper
or signature.

## Reproduction

These are adversarial mutations of the real captured native S05 D5
result at `../../green-value-s05.json`, NOT claims that the producer
normally emits duplicate/corrupt states. The production queue
enqueue/claim/report and real consumer decode path accept them;
production writers persist to an isolated real PocketBase. No fake
writers or LLM calls. Original RED captured before source edits in
red.json/red.log. Final paired replay adds selected-state and replay
checks.

Local PB `d5-a4-pb` remains available on port 42940 for integration,
with owned pb-data here. Port 42941 unused. Observer command, from the
artifact directory:

```sh
docker --context desktop-linux run --rm --platform linux/amd64 --user 0 -v "$PWD:/proof" -v "$PWD/../..:/capture:ro" --entrypoint node showcase-d5-a4:local /proof/proof.mjs green-integration
```

For the baseline use image
`sha256:a7030a6f2e570e72dd01ff78dabc33882b0c2cee8f38c843b07aeb0d34f4f598`,
label `red-integration`. Expected exit 1 baseline, 0 candidate. Run
sequentially on this PB. The Dockerfile's parent resolves to the
baseline; replace result-aggregator.js with final integrated harness
build output, then use `docker --context desktop-linux buildx build
--builder desktop-linux --load --platform linux/amd64 -t
showcase-d5-a4:integration .` and use that image in the observer. Do not
run plain docker build (host default redirects to Depot).

## Validation

113 focused tests pass (four new tests observed failing first). Full
harness: 180 files passed, 2 existing skipped; 3832 tests passed, 18
existing skipped. Typecheck, full TypeScript build, format and lint pass
(eight pre-existing warnings). Language-service diagnostics empty. Local
Docker build succeeded with final emitted module. Receipt hashes bind
source and raw outputs. Manual checks ran before commit; hooks disabled
for commit. Independent CR remains the integration owner's next gate.

## Raw final RED

```jsonl
{"scenario":"duplicate-green-red","consumed":{"processed":1,"failures":0},"summary":{"failed":1,"passed":1,"redsCleared":1,"redsIntroduced":0,"total":2},"state":"failed","history":[{"key":"d5:ms-agent-dotnet/shared-state-write","state":"green"}],"controlsUnchanged":true,"selectedState":"green","replayPreserved":true,"passed":false}
{"scenario":"valid-and-corrupt","consumed":{"processed":1,"failures":0},"summary":{"failed":1,"passed":1,"redsCleared":1,"redsIntroduced":0,"total":2},"state":"failed","history":[{"key":"d5:ms-agent-dotnet/shared-state-write","state":"green"}],"controlsUnchanged":true,"selectedState":"green","replayPreserved":true,"passed":false}
{"scenario":"all-corrupt","consumed":{"processed":1,"failures":0},"summary":{"failed":1,"passed":0,"redsCleared":0,"redsIntroduced":0,"total":1},"state":"failed","history":[],"controlsUnchanged":true,"selectedState":"red","replayPreserved":true,"passed":false}
{"scenario":"explicit-error-with-duplicate","consumed":{"processed":1,"failures":0},"summary":{"failed":1,"passed":1,"redsCleared":1,"redsIntroduced":0,"total":2},"state":"failed","history":[{"key":"d5:ms-agent-dotnet/shared-state-write","state":"green"}],"controlsUnchanged":true,"selectedState":"green","replayPreserved":true,"passed":false}
{"scenario":"comm-duplicate","consumed":{"processed":1,"failures":0},"summary":{"failed":1,"passed":1,"redsCleared":0,"redsIntroduced":0,"total":2},"state":"failed","history":[{"key":"d5:ms-agent-dotnet/shared-state-write","state":"red"}],"controlsUnchanged":true,"selectedState":"red","replayPreserved":true,"passed":false}
```

## Raw final GREEN

```jsonl
{"scenario":"duplicate-green-red","consumed":{"processed":1,"failures":0},"summary":{"failed":0,"passed":1,"redsCleared":1,"redsIntroduced":0,"total":1},"state":"completed","history":[{"key":"d5:ms-agent-dotnet/shared-state-write","state":"green"}],"controlsUnchanged":true,"selectedState":"green","replayPreserved":true,"passed":true}
{"scenario":"valid-and-corrupt","consumed":{"processed":1,"failures":0},"summary":{"failed":0,"passed":1,"redsCleared":1,"redsIntroduced":0,"total":1},"state":"completed","history":[{"key":"d5:ms-agent-dotnet/shared-state-write","state":"green"}],"controlsUnchanged":true,"selectedState":"green","replayPreserved":true,"passed":true}
{"scenario":"all-corrupt","consumed":{"processed":1,"failures":0},"summary":{"failed":0,"passed":0,"redsCleared":0,"redsIntroduced":0,"total":0},"state":"failed","history":[],"controlsUnchanged":true,"selectedState":"red","replayPreserved":true,"passed":true}
{"scenario":"explicit-error-with-duplicate","consumed":{"processed":1,"failures":0},"summary":{"failed":0,"passed":1,"redsCleared":1,"redsIntroduced":0,"total":1},"state":"failed","history":[{"key":"d5:ms-agent-dotnet/shared-state-write","state":"green"}],"controlsUnchanged":true,"selectedState":"green","replayPreserved":true,"passed":true}
{"scenario":"comm-duplicate","consumed":{"processed":1,"failures":0},"summary":{"failed":1,"passed":0,"redsCleared":0,"redsIntroduced":0,"total":1},"state":"failed","history":[{"key":"d5:ms-agent-dotnet/shared-state-write","state":"red"}],"controlsUnchanged":true,"selectedState":"red","replayPreserved":true,"passed":true}
```

</details>

<details><summary>Preserved actual timestamp and creation-race
failure-surface proof</summary>

### Invalid-timestamp counters
## Invalid-timestamp transition counter repair

An accepted green observation with an invalid timestamp leaves the
durable status row red. The aggregator previously counted that
history-only observation as a cleared red. Exclude error transitions and
explicitly non-persisted outcomes from red transition counters.

### Actual local RED → GREEN

Same `round2-invalid-date.mjs` through the official AMD64 harness image,
real queue, real status writer, and local PocketBase atomic endpoint; no
cloud or CI proof. Baseline exit 1; candidate exit 0. The durable status
row stays red in both. This fixes the counter only, not the
intentionally retained durable colour or the separate observation
rollup.

RED raw output:
```text
{"level":"warn","msg":"pb-client.legacy-admin-auth-fallback","ts":"2026-09-17T15:59:54.867Z","hint":"/_superusers returned 404 — falling back to /api/admins (PB ≤0.22). Disable this warn after upgrading to PB 0.23+."}
{"level":"warn","msg":"status-writer.durable-unparseable-observed-at","ts":"2026-09-17T15:59:55.539Z","key":"d5:round2-invalid-date-1789660794730/selected","observedAt":"invalid-timestamp","currentObservedAt":"2026-09-17 15:59:54.730Z","hint":"incoming durable-write observedAt is unparseable — landing the history row with a substituted timestamp and skipping the durable upsert (PB would 400 on a non-date value)"}
{"bugReproduced":true,"state":"red","summary":{"failed":0,"passed":1,"redsCleared":1,"redsIntroduced":0,"selectedObservationFingerprint":"9382bff8aa3105e878dc9886a37996c6a337eea0f9a8f32e6e9403ad27ddc9a2","total":1}}
```
GREEN raw output:
```text
{"level":"warn","msg":"pb-client.legacy-admin-auth-fallback","ts":"2026-09-17T16:07:46.700Z","hint":"/_superusers returned 404 — falling back to /api/admins (PB ≤0.22). Disable this warn after upgrading to PB 0.23+."}
{"level":"warn","msg":"status-writer.durable-unparseable-observed-at","ts":"2026-09-17T16:07:47.688Z","key":"d5:round2-invalid-date-1789661266436/selected","observedAt":"invalid-timestamp","currentObservedAt":"2026-09-17 16:07:46.437Z","hint":"incoming durable-write observedAt is unparseable — landing the history row with a substituted timestamp and skipping the durable upsert (PB would 400 on a non-date value)"}
{"bugReproduced":false,"state":"red","summary":{"failed":0,"passed":1,"redsCleared":0,"redsIntroduced":0,"selectedObservationFingerprint":"714c566c75bc85f99ccdea8b44da79b02366a94a6ab50c75e9d2ac4f59d27a86","total":1}}
```

Candidate local image:
`sha256:09086b2550217c279691c4a4aa9d5a6e8d3c098f5298b386fbeabf6442faae1f`
(linux/amd64), built with the repository's unchanged harness Dockerfile
and the isolated candidate source. Focused regression tests: RED 3
failed /116 passed; GREEN119 passed. Additional complete checks recorded
separately in the final receipt.

Final validation: complete harness suite3841 passed/18 existing skipped;
typecheck and format passed; lint0 errors/8 unchanged baseline warnings.
Clean commit `9ba5f5ff5739d36bf3f02bfb38d7c329e5b4c3b4`; hooks passed
without bypass.


### Selected creation race
## Selected communication-error creation race

A selected observation could miss its live communication-error overlay
when another writer created the status row between the overlay read and
its history fallback. Keep the fallback bound to the absent-row basis. A
concurrent insertion now produces a transaction conflict and repeats
route selection, attaching the diagnostic to the newly created row.

### Actual local red/green proof

Uses the official harness Dockerfile and actual local PocketBase at port
43590. The probe schedules a real foreign status insert after the actual
empty status GET; there are no fake database responses.

- BEFORE edit, official baseline
`showcase-harness:d5-source-5becd15a53`: `round2-creation-race.mjs`
exits **1**. `insertions:1`, returned route `write`, live signal
`{foreign:true}`, replay retains the missing diagnostic (`red.log` and
`red/round2-creation-race-red.json`).
- The stricter assertion version against the same baseline also exits
**1**, `acceptance:false` (`red-strict.log`).
- AFTER, official candidate image
`sha256:4f62614c4c5326332543db86f6bbfe8130b2b8065363e1945d77e0c92267f0e5`:
same foreign-insert scenario exits **0**, `acceptance:true`; returned
route `overlay`, `applied:true`, `historyPersisted:true`. Live signal
includes both the foreign value and communication error; green state,
attribution and failure counter are unchanged. Replay does not alter the
row (`green.log`).
- Independent persisted readback: **PASS** — exactly one foreign
observation history and one selected overlay history; receipt route
`overlay`; replay creates no extra history (`persisted.log`).
- Official Docker build and explicit full `tsc --noEmit`: **PASS**. Full
suite plus source-context reruns covers **3838 passed, 18 existing
skips**, no remaining failures. The initial official build-stage run
lacked fixture sources; those failures and subsequent read-only
source-binding reruns are retained. Normal commit hooks and Prettier
check also pass.

This proves one persistence race; it does not claim any original staging
cell is resolved.


### Rollback test target
## Local red-green proof: rollback test targets the affected job

The old rollback check read the original job instead of the third job
whose transaction failed. Both negative controls PATCH the real private
PocketBase thirdJob receipt and verify that persisted mutation before
the assertion.

```text
RED stale receipt corruption: exit 0 — ALL REAL POCKETBASE TRANSACTION CHECKS PASSED
RED capacity receipt corruption: exit 0 — ALL REAL POCKETBASE TRANSACTION CHECKS PASSED
GREEN same stale corruption: exit 1 — AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal
GREEN same capacity corruption: exit 1 — AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal
GREEN intact real transaction suite: exit 0 — ALL REAL POCKETBASE TRANSACTION CHECKS PASSED
```

Both fixed failures identify the actual persisted `wrongJobControl`
receipt mismatch. Existing real transaction checks stay intact. Syntax,
format, applicable precommit hooks, and commitlint pass.



</details>

## Retained follow-ups

# Retained follow-ups for combined harness shipment

These preserve the two independent review inventories. Selected
observation transactions address the current selected-job write/retry
subject; they do not claim to resolve ordinary unfiltered write/ack
durability or the broader lifecycle subjects. Overlapping descriptions
remain traceable to their original inventories.

## Parent reporting-integrity inventory

# Consolidated follow-ups after round 3

All eighteen remain real, separately scoped follow-up obligations. No
item is erased or declared fixed by this status shipment. D1–D17 retain
their prior independent classifications; D18 is newly confirmed under
the distinct fleet-boot-stop-signal-ownership subject.

# Deferred — Out of Scope for this PR

## Bucket (c) — subject-neutral pre-existing (deferred backlog)

(none)

## Bucket (d) — out-of-this-PR subject (follow-up PR)

- showcase/harness/src/orchestrator.ts:3256 — follow-up: D1 —
Cross-environment pin-drift discovery activation.
- showcase/harness/src/orchestrator.ts:4280/4372 — follow-up: D2 —
Worker registration health recovery.
- showcase/harness/src/orchestrator.ts:2836 — follow-up: D3 — PID
saturation durable recovery.
- showcase/harness/src/fleet/control-plane/result-aggregator.ts:1061 —
follow-up: D4 — At-least-once aggregator write/ack durability.
- showcase/harness/src/probes/loader/probe-invoker.ts:731 — follow-up:
D5 — Detail-aware durable progress counts.
- showcase/harness/src/probes/loader/probe-invoker.ts:733 — follow-up:
D6 — Monotonic concurrent progress persistence.
- showcase/harness/src/probes/loader/probe-invoker.ts:771 — follow-up:
D7 — Invoker sibling cancellation/drain lifecycle.
- showcase/harness/src/orchestrator.test.ts:6325 — follow-up: D8 —
Control-plane test failure cleanup handle.
- showcase/harness/src/orchestrator.test.ts:2061 — follow-up: D9 —
Unregister regression must observe rejected attempt.
- showcase/harness/src/orchestrator.test.ts:4700 — follow-up: D10 —
HTTP-probe test temporary directory cleanup.
- showcase/harness/src/orchestrator.test.ts:1397 — follow-up: D11 — S3
test environment restoration.
- showcase/harness/src/orchestrator.test.ts:1395 — follow-up: D12 — Test
module factory isolation.
- showcase/harness/src/orchestrator.test.ts:235 — follow-up: D13 —
Shutdown regression must verify socket closure.
- showcase/harness/src/orchestrator.ts:1233 — follow-up: D14 — Legacy
boot bind failure leaks watchers, engine and subscriptions.
- showcase/harness/src/orchestrator.ts:3505 — follow-up: D15 —
Control-plane HTTP scheduler last-run cache is not hydrated on restart.
- showcase/harness/src/orchestrator.ts:3387 — follow-up: D16 —
Unserialized asynchronous reloads can restore stale schedule
configuration.
- showcase/harness/src/orchestrator.ts:3607 — follow-up: D17 — Port-zero
boot handles return requested zero instead of assigned port.

- showcase/harness/src/orchestrator.ts:4538 (also 4493) — follow-up: D18
— Fleet boot/stop signal-handler ownership; stopped generations retain
callbacks and can exit before a replacement drains. Independent
classification: round-3-signal-lifecycle-independent-classification.md.

Origin/classification evidence: round-1-complete-inventory.json;
independent-test-finding-classification.md;
runtime-durability-independent-classification.md;
round-2-lifecycle-independent-classification.md;
round-3-signal-lifecycle-independent-classification.md. Canonical
originating reports and line anchors remain in this directory.


## D5 persistence inventory

# Consolidated D5 follow-ups — bucket (d)

These are confirmed separate subjects, not waived defects and not
current D5 mandatory work. Inherited partition evidence:
../../confirmation/round-2-final-partition.md. Current classification:
round-3-final-partition.md. Bucket(c) empty.

1. Ordinary overlay row-deletion recovery: preserve HTTP404 status from
pb-client.update so ordinary overlay fallback classifies a vanished row.
Actual read/delete/PATCH repro required before a behavior fix; verify
selected atomic409 behavior remains intact.
2. Complete orphan-run boot cleanup: sweepStaleRuns currently visits
only first50. Real51+row proof required; bounded pagination must handle
changing rows and failures without infinite retry.
3. Bounded PocketBase transport operation: auth, fetch and body reads
lack one overall deadline. Real stalled auth/headers/body proof
required, including no attempt after deadline. Do not conflate retry
wait budget with total request deadline.
4. Docker/Railway health recovery documentation: HEALTHCHECK unhealthy
status does not itself restart container. Correct operational comment
against actual supervisor behavior; no implicit runtime restart change.
5. Ordinary probe-run lifecycle documentation: failed also includes
reported negative fleet outcomes, not only execution exceptions.
Document both callers without changing policy.
6. PocketBase retry exception documentation: exhausted429/5xx throws
typed PbHttpError, not Response. Correct existing comment; distinct from
implementing deadline #3.

All behavioral follow-up PRs require actual LOCAL RED before fix, SAME
actual GREEN after fix, raw output in PR body. Comment-only work
requires factual verification and emitted-code equivalence. No follow-up
is marked completed here.


## Rollout

After green CI, use normal main build and `:latest` staging deployments
for both control plane and worker. Verify both deployed
revisions/digests, then enqueue normal selected D5 runs and inspect
fresh persistence and dashboard results. No image pins, status
overrides, or direct staging database edits. Close superseded #7222 only
after this PR merges.
JadeCong pushed a commit to CloudEngineHub/CopilotKit that referenced this pull request Oct 10, 2026
…-time review

Addresses 5 Important review findings on the Task 5 commit plus 2
controller rulings.

1. CopilotChat.tsx's run-activity effect listed `copilotkit.headers` in
   its deps. A builder's snapshot object churns on every resolve, so a
   run followed by any re-render tore down and rebuilt the standalone
   run-activity store's subscription for no reason (extra
   setContext/stop/start, and a detachActiveRun when wake-reconnect was
   active). Fixed to `copilotkit.ɵheadersGeneration`, matching
   use-threads.tsx's existing pattern.

   Controller ruling: `HeaderSourceResolver.accept()` (core) now keeps
   the previous snapshot object when a resolve's normalized result is
   shallow-equal to it (same keys, same values), so `core.headers`
   only gets a new reference when a header value actually changed --
   this is what makes headers-as-a-dep safe anywhere in react-core/vue/
   angular, not just in the one call site fixed above.

2. The 20-rerenders memo-stability test had no `publicApiKey`, so
   `ɵwithHeaderDefaults`'s empty-defaults passthrough masked a
   deps-only mutation (adding `headersProp` to the deps without
   touching the factory). Added a `publicApiKey` row: with real
   defaults present, `ɵwithHeaderDefaults` wraps in a NEW closure on
   every call, so a deps-only "obvious fix" now genuinely breaks it.

3. The R3 annotation test was circular: the mock had no
   `copilotkit.headers` snapshot, and the mock `ɵruntimeFetch` wrote
   its header AFTER spreading `init.headers`, so a reintroduced stale
   spread would have been silently overwritten either way. Rewrote it
   to give the mock a snapshot with a key the current source cannot
   produce, and assert that key is ABSENT from the sent request (the
   mock no longer masks a regression). Added the missing
   use-learning-containers coverage: both Effect 1's mount emit and
   Effect 2's cleanup/reset emit now have their own snapshot-absence
   test.

4. StrictMode rows only asserted `/info` called once. Added: the
   connection actually reaches Connected, the `/info` request's
   Authorization matches the builder's resolved value (including the
   async row), a `connect()` spy proving the mount effect really
   double-invoked (2 calls), a 4th row (inline builder + publicApiKey),
   and a 50ms (not 30ms) settle window.

5. Controller ruling: `headersRef.current = headersProp` is now
   assigned during render, not inside a passive `useEffect`. React
   fires a child's effects before its parent's own effects
   (bottom-up); if only the provider's effect updated the ref, a child
   effect that fires a request in the SAME commit as a new builder
   closure would still read the previous commit's closure. Verified
   with a plain (non-proxied) HttpAgent -- deliberately NOT wrapped
   with `ɵruntimeFetch`, so `prepareAgentHeadersForRun`'s one
   synchronous resolution is the only place the token can land, with
   no send-time safety net to mask the race.

Mutation checks (all restored after confirming failure):
- CopilotKit#1: CopilotChat.tsx dep reverted to `copilotkit.headers` -> new
  run-activity test failed (3 unwanted setContext/start/stop calls
  instead of 0).
- CopilotKit#1 (core ruling): `accept()` reverted to always replace the
  snapshot -> both new core-header-source tests failed (`toBe` on
  object identity).
- CopilotKit#2: `headersProp` added to the deps array only (factory untouched)
  -> the "with publicApiKey" row failed (20 setHeaders calls); the
  "no publicApiKey" row still passed, exactly as the review predicted.
- CopilotKit#3: put `copilotkit.headers ?? {}` back in use-learn-from-user-action
  and in both use-learning-containers effects -> all three new
  snapshot-absence tests failed.
- CopilotKit#4: commented out `copilotkit.connect()` in the reconnect effect ->
  all 4 StrictMode rows failed on the new Connected-status assertion.
  (A `setHeaders({})` or `setRuntimeUrl` toggle in the effect's own
  cleanup, as the review suggested by example, does NOT reproduce a
  failure here: the effect's setup unconditionally re-applies every
  setter before calling `connect()` again on the second StrictMode
  invoke, so anything a mutation confined to cleanup changes gets
  healed by the very next setup pass. Documented so a future pass
  doesn't re-attempt the same example expecting it to fail.)
- CopilotKit#5: moved `headersRef.current = headersProp` back into a passive
  `useEffect` -> the new same-commit test failed (`agent.headers`
  carried the stale "Bearer tok-1" instead of "Bearer tok-2").

Verification:
- `NX_NO_CLOUD=true pnpm nx run @copilotkit/react-core:test --skip-nx-cache`
  -> 159 files / 1747 tests, all green.
- `NX_NO_CLOUD=true pnpm nx run @copilotkit/core:test --skip-nx-cache`
  -> 81 files / 1002 tests, all green.
- `NX_NO_CLOUD=true pnpm nx run @copilotkit/core:check-types --skip-nx-cache`
  and `NX_NO_CLOUD=true pnpm nx run @copilotkit/react-core:check-types --skip-nx-cache`
  -> both clean.
- Core dist rebuilt (`nx run @copilotkit/core:build --skip-nx-cache`)
  after the header-source.ts change, before re-running react-core.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
BenTaylorDev added a commit that referenced this pull request Nov 6, 2026
…lterable (#8244)

Item #3 of the PostHog cost-reduction plan (Notion: "PostHog cost
reduction — decisions").

## Problem

`showcase/shell-docs/src/middleware.ts` sends one `docs_pageview` per
ordinary docs page request, about 7.1M events a month. The event carried
only `path`:

- No `$process_person_profile`, so every event created or updated a
person profile and billed at the identified rate.
- Bots and agents never return the `ph_distinct_id` cookie, so each of
their hits minted a new person.
- No user agent, so PostHog's bot filter classified 100% of these events
as `no_user_agent` (Automation).
- No `$ip`, so GeoIP located our server, not the visitor.

## Change

- `docs_pageview` now sends `$process_person_profile: false`, `$ip`
(from the existing `clientIp(request)`), `$raw_user_agent` (capped at
512 characters, like the llm-text path), `environment` and `referrer`.
`captureLlmTextFetch` is the model. `$geoip_disable` is NOT set: with
`$ip` set to the visitor's address, GeoIP is now correct.
- The id cookie is renamed from `ph_distinct_id` to `ph_docs_id`, so
every visitor gets a new id. This is required. PostHog upgrades a
distinct_id that already has a person back to identified processing even
when the flag is false (`person_mode = force_upgrade`). Without the
rotation, the flag saves almost nothing. A grep of this repo,
Intelligence and oss-path-to-production found no other reader of
`ph_distinct_id` (posthog-js bootstraps only `sessionID` from a URL
param).
- `seo_redirect` gets the same flag, `$ip` and `$raw_user_agent`. Its
fixed distinct_id changes from `seo-redirect-tracker` to `seo-redirect`,
for the same `force_upgrade` reason: the old id already has a person
profile.

Unchanged: the event names, the `docs_pageview` `path` property (five
saved insights read them: rBWKLsAB, lZHWczTd, dD6IV5x1, qJGVQswb,
KIQFqFvp), posthog-js and the browser `$pageview`, and the prefetch,
llm-text and redirect behavior.

## Expected effects

- Event counts are unchanged.
- Unique-person counts on `docs_pageview` drop. There is a one-time
break at cutover because of the cookie rotation. This is expected.

## Follow-up (#5)

After this deploys, enable PostHog's "Filter Bot Events" transformation
on `$raw_user_agent`. Do not enable it before this ships: today no event
carries a user agent, so the filter would drop everything.

## Testing

New tests in `showcase/shell-docs/src/middleware.test.ts`:

- Cookie minted: `docs_pageview` body has the flag, `$ip`,
`$raw_user_agent`, `referrer`, `environment`, no `$geoip_disable`.
`Set-Cookie` sets `ph_docs_id` to the event's distinct_id.
- Cookie present (`ph_docs_id`): the id is reused, the same properties
are sent, and no cookie is set.
- Retired cookie (`ph_distinct_id` only): ignored, and a new
`ph_docs_id` is minted.
- User agent capped at 512 on the pageview path.
- `seo_redirect`: flag, `$ip`, `$raw_user_agent`, and the old
distinct_id is no longer used.

```
$ vitest run src/middleware.test.ts
 Test Files  1 passed (1)
      Tests  18 passed (18)
```

Mutation check: each mutation reddens the new tests.

```
# cookie name reverted to "ph_distinct_id"
      Tests  3 failed | 15 passed (18)
# $process_person_profile and the pageview caller properties removed
      Tests  4 failed | 14 passed (18)
```

Full shell-docs suite: all 432 tests that ran pass. Six suites fail to
load because the local `node_modules` lacks `jsdom`, `@clerk/nextjs`,
`embla-carousel-wheel-gestures` and a built `@copilotkit/react-core/v2`.
None of them import the middleware.

```
 Test Files  6 failed | 61 passed (67)
      Tests  432 passed (432)
```

`oxlint` (0 warnings, 0 errors), `oxfmt --check` (clean) and
`scripts/validate-intelligence-env-names.ts` (pass) were run by hand on
the changed files. `tsc --noEmit` reports no errors in the middleware
files. Its only errors are the same missing-package errors listed above.

🤖 Generated with [Claude Code](https://claude.com/claude-code)


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **Updates**
* Documentation pageviews and SEO redirects now include request context,
including caller IP and a user-agent value capped at 512 characters.
* Pageview tracking preserves referrer and environment details, and
redirect tracking records the relevant paths.
* Documentation pageviews now use a dedicated cookie for visitor IDs.
Existing IDs in the previous cookie are no longer reused.
  * Person-profile processing is disabled for these tracking events.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
ayuxy027 pushed a commit to ayuxy027/CopilotKit-Ayush.dev that referenced this pull request Nov 13, 2026
…he post-release smoke test (CopilotKit#8018)

## What does this PR do?

Two workflow fixes: showcase auto-approval checks every changed file and
only accepted team members, and the post-release starter smoke test runs
again.

**1. Showcase auto-approval.** `auto_merge_showcases.yml` approves a
Demo-team PR and turns on auto-merge when it only touches
`examples/showcases/`. Two gaps:
- `pulls.listFiles` was called once with `per_page: 100` and no
pagination, so for a PR with more than 100 files only the first page was
checked. A file outside showcases on a later page didn't block approval.
It now uses `github.paginate`.
- The endpoint returns at most 3,000 files, so the workflow now also
fails closed when the list is shorter than the PR's `changed_files`.
- `getMembershipForUserInOrg` also returns 200 for a pending invitation,
and `data.state` wasn't checked. Only `state === "active"` counts now.

**2. The post-release smoke test never ran.** `test_smoke-starter.yml`
listens for `workflow_run` of `"publish / release"`, but the release
workflow is named `"release / publish"`. So the trigger never fired: the
full-fleet run after each release, and its Slack failure alert (both
written specifically for `workflow_run`), have been silently skipped.
The trigger now uses the real name, and the zizmor suppression note that
repeats the name is corrected too.

## Testing

**The approval logic.** I parsed the workflow YAML and ran the two
`github-script` steps against a mocked GitHub API (real pagination
behaviour: pages of 100 until a short page):

| | `main` | this PR |
|---|---|---|
| active member, 150 files, a `packages/core` file on page 2 |
auto-approved | not approved |
| active member, 3,001 files, the non-showcase file is CopilotKit#3,001 |
auto-approved | not approved |
| pending member, showcase-only files | auto-approved | not approved |
| active member, showcase-only files | auto-approved | auto-approved |

**The trigger.** Parsing every workflow's `name`: on `main`, `"publish /
release"` matches no workflow; on this branch, `"release / publish"`
matches `publish-release.yml`. All three edited files parse as YAML. I
didn't run actionlint or zizmor locally; CI runs them.

## Checklist

- [x] I have read the [Contribution
Guide](https://github.com/copilotkit/copilotkit/blob/master/CONTRIBUTING.md)
- [x] If the PR changes or adds functionality, I have updated the
relevant documentation (no doc change needed)
- [x] If the PR contains a breaking change, the title has `!` (not a
breaking change)
- [x] "Allow edits by maintainers" is checked

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **Chores**
* Showcase checks now require active team membership and verify that the
complete changed-file list contains only showcase files. Incomplete
listings prevent approval and auto-merge.
* Starter smoke tests now require the release workflow’s upstream run
and build job to succeed, or a manual run on `main`. Other
non-workflow-run triggers remain allowed. Related configuration now
reflects the updated release workflow name.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
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.

1 participant