Skip to content

Commit bd5237c

Browse files
committed
Merge remote-tracking branch 'upstream/main' into remove-dead-debug-log-flags
2 parents a3b0c26 + 20012eb commit bd5237c

39 files changed

Lines changed: 1956 additions & 272 deletions

‎.github/workflows/mobile-eas-preview.yml‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,10 @@ jobs:
6666
if: steps.expo-token.outputs.present == 'true'
6767
uses: expo/expo-github-action@v8
6868
with:
69-
eas-version: latest
69+
# eas-cli 22 renamed `project` to `app` in build JSON, and
70+
# continuous-deploy-fingerprint still reads `build.project.ownerAccount`.
71+
# Unpin once https://github.com/expo/expo-github-action/issues/358 is fixed.
72+
eas-version: 21.8.0
7073
token: ${{ secrets.EXPO_TOKEN }}
7174
# npm, not pnpm: this only installs eas-cli into the action's own
7275
# tool dir, and pnpm 11 hard-fails that install on dtrace-provider's

‎.macroscope/check-run-agents/effect-service-conventions.md‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ showToolCalls: true
2222

2323
# Effect service review
2424

25-
Review changed TypeScript for the conventions below. They apply when a pull request creates, moves, refactors, or consumes an Effect service. Review only the lines the PR changed; older code in the same file that predates these conventions is not a finding. Do not demand repository-wide cleanup.
25+
Review changed TypeScript for the conventions below. They apply when a pull request creates, moves, refactors, or consumes an Effect service, or adds server behavior. Authors read the same rules in `docs/internals/effect-services.md`; keep the two in step. Review only the lines the PR changed; older code in the same file that predates these conventions is not a finding. Do not demand repository-wide cleanup.
2626

2727
## Imports and module namespaces
2828

@@ -31,11 +31,16 @@ Review changed TypeScript for the conventions below. They apply when a pull requ
3131
- Named imports stay correct for whole packages such as `@t3tools/contracts` and for modules used only for a pure helper, error, schema, config value, or type. Do not request `import type * as Contracts`.
3232
- When a barrel exposes a whole service module, prefer `export * as TokenStore from "./tokenStore.ts"` over individually renamed `make` and `layer` exports.
3333

34+
## Placement
35+
36+
- Flag new or broadened feature logic in a transport handler: a WebSocket RPC handler in `apps/server/src/ws.ts`, an HTTP route handler, or an MCP tool handler. A handler decodes input, calls one service method, and maps the service's errors to the transport's error. Filesystem, Git, process, or persistence work, folder naming, multi-step command dispatch, retries, or rollback inside a handler belongs in a service method; ask for it to move to the domain's existing service, or a new one when none owns the domain. Existing inline handlers are legacy; flag only changed lines.
37+
- Flag a new exported free function that does a server capability's effectful work (filesystem, Git, processes, persisted state) and is called from a handler, when it should be a service method. Plain functions for pure work (formatting, naming, parsing) are fine.
38+
3439
## Service definition
3540

3641
- One canonical module per service in this order: imports, error and schema declarations, the `Context.Service` tag with its interface inline, `make`, then `layer`.
3742
- Define the interface inline in `Context.Service`. Do not add a standalone `FooShape` interface; refer to the inferred type as `Foo["Service"]`.
38-
- Export a real `make` when the module owns construction. Do not write `make = Effect.succeed(...)` only to force `Layer.effect`; use `Layer.succeed`, `Layer.scoped`, or whichever constructor matches.
43+
- Define a real `make` when the module owns construction, and export it only when another module imports it; knip fails CI on an unused export, so do not ask for an export nothing uses. Do not write `make = Effect.succeed(...)` only to force `Layer.effect`; use `Layer.succeed`, `Layer.scoped`, or whichever constructor matches.
3944
- Use plain `make` and `layer` in a module named for its implementation (`BunPtyAdapter.ts`). Keep implementation-specific names when one abstract port module holds several implementations (`makeCloudflaredRelayClient`, `layerCloudflared` in `RelayClient.ts`). `infra/relay/src/db.ts` may keep its inline `Layer.succeed(RelayDb, db)`.
4045
- When a service moves, delete the old files and update every consumer, including orchestration, MCP, tests, and integration harnesses. Do not leave compatibility re-export shims.
4146

‎AGENTS.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ The most common defect in this repo is a change that works on the path you teste
6969
- **Entry points.** A behavior reachable from the chat view is usually also reachable from Settings, the command palette, and a keybinding. Fixing one is not fixing the feature.
7070
- **Clients.** Web, desktop (wraps web, adds Electron shell/IPC), and mobile (React Native, separate navigation). Shared logic lives in `packages/client-runtime`
7171
- **Providers.** Codex, Claude, Cursor, Grok, OpenCode, and Antigravity each have an adapter. Provider-shaped features need a decision per adapter, even if the decision is "not supported here".
72+
- **Agents.** A capability a user can trigger is usually one an agent should reach through MCP tools, and scheduled tasks run the same paths. That only works when it is a service method, not handler code.
7273
- **Contracts.** Anything crossing the wire is typed in `packages/contracts`. Change the schema and the server, web, mobile, and desktop all follow.
7374
- **Reverse states.** If you added a way in, add the way out and the way to see it. Snooze needs unsnooze. Close needs reopen. A one-way door is a bug.
7475
- **Connection modes.** Local, remote/relay, and tunnel behave differently. Multi-device and multi-environment cases are real.
@@ -148,7 +149,7 @@ Full glossary with file links: `docs/internals/glossary.md`
148149

149150
## Where code lives
150151

151-
- `apps/server` - WebSocket, orchestration, providers, checkpointing. Effect-heavy: read `.repos/effect-smol/LLMS.md` before writing Effect code.
152+
- `apps/server` - WebSocket, orchestration, providers, checkpointing. Effect-heavy: read [Effect services](docs/internals/effect-services.md) before adding server code, and `.repos/effect-smol/LLMS.md` for the Effect library itself.
152153
- `apps/web` - React/Vite UI. `apps/desktop` wraps it, `apps/mobile` is React Native, `apps/marketing` is the site.
153154
- `packages/contracts` - Effect/Schema contracts plus small derived helpers. No heavy runtime logic.
154155
- `packages/shared` - shared runtime utils, subpath exports, no barrel.
@@ -158,6 +159,7 @@ Full glossary with file links: `docs/internals/glossary.md`
158159
## Taste
159160

160161
- Complexity belongs at the adapter boundary. Orchestration stays pure, UI stays dumb.
162+
- Server features are services; transports stay thin. A `ws.ts` RPC handler, HTTP route, or MCP tool decodes input, calls one service method, and maps errors. See [Effect services](docs/internals/effect-services.md).
161163
- `apps/web/src/components/ui` exports own their look. Pick a `variant` or `size`; do not restyle one with `className`. If none fits and the look is a generic concept, add a variant to the component; a look that belongs to one feature stays in that feature's own component, not in `components/ui`. Layout classes (width, flex, margin, position) belong on the parent. `shadcn/no-restyle` fails lint on violations.
162164
- Inferred types over annotations. `any` is the enemy.
163165
- Comments describe how a thing is used, and move when the code moves. To be used mostly to describe functions, not to annotate every line of behavior.

‎apps/desktop/src/settings/DesktopClientSettings.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ const clientSettings: ClientSettings = {
6565
sidebarThreadSortOrder: "created_at",
6666
sidebarThreadPreviewCount: 6,
6767
legacySidebarEnabled: false,
68+
sidebarWorkingShelfEnabled: false,
6869
loadBalancingEnabled: false,
6970
loadBalancingWeights: { "environment-1": 75, "environment-2": 0 },
7071
pullRequestMergeMethodOverrides: {},

‎apps/server/src/git/GitManager.test.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import * as Logger from "effect/Logger";
1313
import * as Option from "effect/Option";
1414
import * as PlatformError from "effect/PlatformError";
1515
import * as References from "effect/References";
16+
import * as Result from "effect/Result";
1617
import * as Schema from "effect/Schema";
1718
import * as Scope from "effect/Scope";
1819
import { TestClock } from "effect/testing";
@@ -32,6 +33,7 @@ import {
3233
TextGenerationError,
3334
} from "@t3tools/contracts";
3435
import * as GitHubCli from "../sourceControl/GitHubCli.ts";
36+
import { decodeGitHubPullRequestListJson } from "../sourceControl/gitHubPullRequests.ts";
3537
import * as GitLabCli from "../sourceControl/GitLabCli.ts";
3638
import * as TextGeneration from "../textGeneration/TextGeneration.ts";
3739
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
@@ -510,6 +512,30 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
510512
return {
511513
service: {
512514
execute,
515+
// The fake answers the CLI shape, so batched lookups read it the way the fallback does.
516+
listPullRequestsByHead: (input) =>
517+
execute({
518+
cwd: input.cwd,
519+
args: [
520+
"pr",
521+
"list",
522+
"--head",
523+
input.headSelector,
524+
"--state",
525+
input.state,
526+
"--limit",
527+
String(input.limit),
528+
"--json",
529+
"number,title,url,baseRefName,headRefName,state,isDraft,mergedAt,closedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
530+
],
531+
}).pipe(
532+
Effect.map((result) => {
533+
const raw = result.stdout.trim();
534+
if (raw.length === 0) return [];
535+
const decoded = decodeGitHubPullRequestListJson(raw);
536+
return Result.isSuccess(decoded) ? decoded.success : [];
537+
}),
538+
),
513539
listOpenPullRequests: (input) =>
514540
execute({
515541
cwd: input.cwd,

‎apps/server/src/orchestration/PullRequestSyncReactor.test.ts‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -754,6 +754,88 @@ describe("PullRequestSyncReactor", () => {
754754
),
755755
);
756756

757+
it.effect("reads a burst of requested links in one sweep", () =>
758+
Effect.scoped(
759+
Effect.gen(function* () {
760+
yield* TestClock.setTime(Date.parse(NOW));
761+
const reading = yield* Deferred.make<void>();
762+
const release = yield* Deferred.make<void>();
763+
const fixture = yield* makeHarness({
764+
snapshot: makeSnapshot([]),
765+
summary: (input) =>
766+
Effect.gen(function* () {
767+
if (input.number === 1) {
768+
yield* Deferred.succeed(reading, undefined);
769+
yield* Deferred.await(release);
770+
}
771+
return makeSummary(input);
772+
}),
773+
});
774+
yield* Effect.gen(function* () {
775+
const reactor = yield* startAndSweep(fixture);
776+
yield* Ref.set(
777+
fixture.snapshots,
778+
makeSnapshot(
779+
[1, 2, 3, 4].map((number) =>
780+
makeThread(`thread-${number}`, { pullRequests: [makeLink(number)] }),
781+
),
782+
),
783+
);
784+
const request = (number: number) =>
785+
reactor.requestSync({ host: "github.com", repository: "owner/repository", number });
786+
yield* request(1);
787+
yield* Deferred.await(reading);
788+
yield* Effect.forEach([2, 3, 4], request, { discard: true });
789+
yield* Deferred.succeed(release, undefined);
790+
yield* reactor.drain;
791+
// One sweep for the first link and one for the three that arrived while it read.
792+
assert.strictEqual(yield* Queue.size(fixture.snapshotReads), 2);
793+
assert.deepStrictEqual(
794+
(yield* Ref.get(fixture.summaryCalls)).map((ref) => ref.number).toSorted(),
795+
[1, 2, 3, 4],
796+
);
797+
}).pipe(Effect.provide(fixture.layer));
798+
}),
799+
),
800+
);
801+
802+
it.effect("skips the stack read for a pull request the summary places in no stack", () =>
803+
Effect.scoped(
804+
Effect.gen(function* () {
805+
yield* TestClock.setTime(Date.parse(NOW));
806+
const fixture = yield* makeHarness({
807+
snapshot: makeSnapshot([
808+
makeThread("unstacked", { pullRequests: [makeLink(1)] }),
809+
makeThread("stacked", { pullRequests: [makeLink(2)] }),
810+
makeThread("unknown", { pullRequests: [makeLink(3)] }),
811+
]),
812+
summary: (input) =>
813+
Effect.succeed(
814+
makeSummary(
815+
input,
816+
input.number === 1
817+
? { stack: null }
818+
: input.number === 2
819+
? { stack: { number: 9, position: 1, size: 2, base: "main" } }
820+
: {},
821+
),
822+
),
823+
});
824+
yield* Effect.gen(function* () {
825+
yield* startAndSweep(fixture);
826+
assert.deepStrictEqual(
827+
(yield* Ref.get(fixture.stackCalls)).map((ref) => ref.number).toSorted(),
828+
[2, 3],
829+
);
830+
assert.deepStrictEqual(
831+
(yield* Ref.get(fixture.syncCommands)).map((command) => command.number).toSorted(),
832+
[1, 2, 3],
833+
);
834+
}).pipe(Effect.provide(fixture.layer));
835+
}),
836+
),
837+
);
838+
757839
it.effect("polls open pull requests on settled threads every fifteen minutes", () =>
758840
Effect.scoped(
759841
Effect.gen(function* () {

‎apps/server/src/orchestration/PullRequestSyncReactor.ts‎

Lines changed: 41 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,9 @@ export const make = Effect.gen(function* () {
133133
const lastSyncedAt = new Map<string, number>();
134134
const requested = new Map<string, number>();
135135
let requestGeneration = 0;
136+
// Requested keys wait in `requested` for one queued sweep, so a burst of links (an agent
137+
// linking dozens of pull requests) is read together and shares the summary batches.
138+
let requestedSweepQueued = false;
136139
const retryStacks = new Set<string>();
137140

138141
const isDue = (key: string, entries: ReadonlyArray<LinkEntry>, nowMs: number): boolean => {
@@ -151,7 +154,8 @@ export const make = Effect.gen(function* () {
151154
<E>(cause: Cause.Cause<E>): Effect.Effect<void, E> =>
152155
Cause.hasInterruptsOnly(cause) ? Effect.failCause(cause) : Effect.logWarning(message, fields);
153156

154-
const sweep = Effect.fn("PullRequestSyncReactor.sweep")(function* (requestedKey?: string) {
157+
/** `requested` reads only keys asked for through `requestSync`; `all` is the periodic pass. */
158+
const sweep = Effect.fn("PullRequestSyncReactor.sweep")(function* (scope: "all" | "requested") {
155159
const threads = yield* snapshots.listThreadsWithPullRequests();
156160
const now = yield* DateTime.now;
157161
const nowMs = DateTime.toEpochMillis(now);
@@ -250,22 +254,31 @@ export const make = Effect.gen(function* () {
250254
retryStacks.has(key) ||
251255
entries.some(
252256
(entry) =>
253-
entry.link.snapshot === null || !snapshotFieldsEqual(entry.link.snapshot, fields),
257+
entry.link.snapshot === null ||
258+
!snapshotFieldsEqual(entry.link.snapshot, fields) ||
259+
(summary.stack !== undefined &&
260+
(entry.link.stack?.number ?? null) !== (summary.stack?.number ?? null)),
254261
);
255-
const fetchedStack = needsStack
256-
? yield* pullRequests.stack(ref, { includeDetails: false }).pipe(
257-
Effect.map((stack) => ({
258-
stack: stack === null ? null : ({ kind: "native", ...stack } as const),
259-
})),
260-
Effect.catchCauseIf(
261-
(cause) => !Cause.hasInterruptsOnly(cause),
262-
() =>
263-
Effect.logWarning("pull request stack lookup failed", {
264-
key,
265-
}).pipe(Effect.as(null)),
266-
),
267-
)
268-
: null;
262+
// A summary that says the pull request is in no stack, for links that hold none, already
263+
// answers what the stack read would.
264+
const knownUnstacked =
265+
summary.stack === null && entries.every((entry) => entry.link.stack === null);
266+
const fetchedStack = !needsStack
267+
? null
268+
: knownUnstacked
269+
? { stack: null }
270+
: yield* pullRequests.stack(ref, { includeDetails: false }).pipe(
271+
Effect.map((stack) => ({
272+
stack: stack === null ? null : ({ kind: "native", ...stack } as const),
273+
})),
274+
Effect.catchCauseIf(
275+
(cause) => !Cause.hasInterruptsOnly(cause),
276+
() =>
277+
Effect.logWarning("pull request stack lookup failed", {
278+
key,
279+
}).pipe(Effect.as(null)),
280+
),
281+
);
269282
if (needsStack) {
270283
if (fetchedStack === null) {
271284
retryStacks.add(key);
@@ -296,7 +309,7 @@ export const make = Effect.gen(function* () {
296309
yield* Effect.forEach(
297310
groups,
298311
([key, entries]) =>
299-
(requestedKey === undefined || requestedKey === key) && isDue(key, entries, nowMs)
312+
(scope === "all" || requested.has(key)) && isDue(key, entries, nowMs)
300313
? syncGroup(key, entries).pipe(
301314
Effect.catchCause(logSkipped("pull request sync skipped", { key })),
302315
)
@@ -307,8 +320,12 @@ export const make = Effect.gen(function* () {
307320
);
308321
});
309322

310-
const worker = yield* makeDrainableWorker((key: string | undefined) =>
311-
sweep(key).pipe(Effect.catchCause(logSkipped("pull request sync sweep failed", {}))),
323+
const worker = yield* makeDrainableWorker((scope: "all" | "requested") =>
324+
Effect.suspend(() => {
325+
// Requests from here on queue another sweep; the ones already recorded are read by this.
326+
if (scope === "requested") requestedSweepQueued = false;
327+
return sweep(scope);
328+
}).pipe(Effect.catchCause(logSkipped("pull request sync sweep failed", {}))),
312329
);
313330

314331
const start: PullRequestSyncReactor["Service"]["start"] = Effect.fn(
@@ -322,17 +339,18 @@ export const make = Effect.gen(function* () {
322339
);
323340
yield* forkParked(
324341
Effect.gen(function* () {
325-
yield* worker.enqueue(undefined);
342+
yield* worker.enqueue("all");
326343
yield* worker.drain;
327344
}).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.asVoid),
328345
);
329346
});
330347

331348
const requestSync: PullRequestSyncReactor["Service"]["requestSync"] = (key) =>
332349
Effect.suspend(() => {
333-
const syncKey = threadPullRequestKeyOf(key);
334-
requested.set(syncKey, ++requestGeneration);
335-
return worker.enqueue(syncKey);
350+
requested.set(threadPullRequestKeyOf(key), ++requestGeneration);
351+
if (requestedSweepQueued) return Effect.void;
352+
requestedSweepQueued = true;
353+
return worker.enqueue("requested");
336354
});
337355

338356
return { start, drain: worker.drain, requestSync } satisfies PullRequestSyncReactor["Service"];

‎apps/server/src/orchestration/ThreadPullRequestReactor.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -348,7 +348,9 @@ export const make = Effect.gen(function* () {
348348
}).pipe(Effect.tap(() => Effect.sync(() => failBackfill(group)))),
349349
),
350350
),
351-
{ concurrency: 8, discard: true },
351+
// Wide enough that a sweep's GitHub branch lookups reach GitHubCli together and share one
352+
// GraphQL document, instead of one `gh pr list` per branch.
353+
{ concurrency: 32, discard: true },
352354
);
353355
});
354356

‎apps/server/src/pullRequest/GitHubPullRequestCli.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1821,7 +1821,12 @@ export const make = Effect.gen(function* () {
18211821
const batchable = entries.filter(
18221822
(entry) => buildPullRequestSummariesGraphQlQuery([entry.request]) !== null,
18231823
);
1824-
const query = buildPullRequestSummariesGraphQlQuery(batchable.map((entry) => entry.request));
1824+
// Stack membership rides along where GitHub serves stacks, so the background sync can skip
1825+
// the REST stack read for pull requests that are in none.
1826+
const query = buildPullRequestSummariesGraphQlQuery(
1827+
batchable.map((entry) => entry.request),
1828+
first.request.host === "github.com",
1829+
);
18251830
const batched =
18261831
query === null
18271832
? Effect.succeed(new Map<number, GitHubPullRequestSummary>())

‎apps/server/src/pullRequest/PullRequestProvider.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,11 @@ export interface ProviderChangeRequestSummary {
116116
readonly reviewDecision?: PullRequestReviewDecision | null | undefined;
117117
readonly checksState?: PullRequestChecksState | null | undefined;
118118
readonly mergeability?: PullRequestMergeability | undefined;
119+
/**
120+
* The host-native stack the pull request sits in, from the same read. Null when the host says
121+
* it is in none; absent when the read did not ask.
122+
*/
123+
readonly stack?: PullRequestStackMembership | null | undefined;
119124
}
120125

121126
/** One layer of a host-native stack, bottom to top order is the array's. */

0 commit comments

Comments
 (0)